Skip to content

Commit a078848

Browse files
committed
Added : Same Tree
1 parent b967727 commit a078848

File tree

2 files changed

+59
-0
lines changed

2 files changed

+59
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
Given two binary trees, write a function to check if they are the same or not.
2+
3+
Two binary trees are considered the same if they are structurally identical and the nodes have the same value.
4+
5+
Example 1:
6+
7+
Input: 1 1
8+
/ \ / \
9+
2 3 2 3
10+
11+
[1,2,3], [1,2,3]
12+
13+
Output: true
14+
Example 2:
15+
16+
Input: 1 1
17+
/ \
18+
2 2
19+
20+
[1,2], [1,null,2]
21+
22+
Output: false
23+
Example 3:
24+
25+
Input: 1 1
26+
/ \ / \
27+
2 1 1 2
28+
29+
[1,2,1], [1,1,2]
30+
31+
Output: false
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
/**
2+
@lc id : 100
3+
@problem : Same Tree
4+
@author : rohit
5+
@date : 13/07/2020
6+
@url : https://leetcode.com/problems/same-tree/
7+
*/
8+
9+
class Solution {
10+
11+
public boolean isSameTree(TreeNode p, TreeNode q) {
12+
13+
//Both trees are null
14+
if(p == null && q == null)
15+
return true;
16+
17+
//One Tree is null
18+
if( (p == null && q != null) || ( p != null && q == null ))
19+
return false;
20+
21+
//Tree Root has same val
22+
if(p.val == q.val)
23+
return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
24+
25+
return false;
26+
27+
}
28+
}

0 commit comments

Comments
 (0)