Skip to content

Commit 618b11d

Browse files
committed
Same Tree
1 parent 5f4864e commit 618b11d

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

Same Tree.js

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
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+
6+
Example 1:
7+
8+
Input: 1 1
9+
/ \ / \
10+
2 3 2 3
11+
12+
[1,2,3], [1,2,3]
13+
14+
Output: true
15+
Example 2:
16+
17+
Input: 1 1
18+
/ \
19+
2 2
20+
21+
[1,2], [1,null,2]
22+
23+
Output: false
24+
Example 3:
25+
26+
Input: 1 1
27+
/ \ / \
28+
2 1 1 2
29+
30+
[1,2,1], [1,1,2]
31+
32+
Output: false*/
33+
34+
/**
35+
* Definition for a binary tree node.
36+
* function TreeNode(val) {
37+
* this.val = val;
38+
* this.left = this.right = null;
39+
* }
40+
*/
41+
/**
42+
* @param {TreeNode} p
43+
* @param {TreeNode} q
44+
* @return {boolean}
45+
*/
46+
var isSameTree = function(p, q) {
47+
if(p==null && q==null)
48+
return true
49+
if(p==null || q==null)
50+
return false
51+
if(p.val != q.val)
52+
return false
53+
return isSameTree(p.left,q.left) && isSameTree(p.right,q.right)
54+
};

0 commit comments

Comments
 (0)