Skip to content

Commit bf5a3c6

Browse files
committed
feat: 100. Same Tree
1 parent cf5691a commit bf5a3c6

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed

same-tree/gwbaik9717.js

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
// n: number of nodes
2+
// Time complexity: O(n)
3+
// Space complexity: O(n)
4+
5+
/**
6+
* Definition for a binary tree node.
7+
* function TreeNode(val, left, right) {
8+
* this.val = (val===undefined ? 0 : val)
9+
* this.left = (left===undefined ? null : left)
10+
* this.right = (right===undefined ? null : right)
11+
* }
12+
*/
13+
/**
14+
* @param {TreeNode} p
15+
* @param {TreeNode} q
16+
* @return {boolean}
17+
*/
18+
var isSameTree = function (p, q) {
19+
const dfs = (currentP, currentQ) => {
20+
if (currentP.val !== currentQ.val) {
21+
return false;
22+
}
23+
24+
if (
25+
(currentP.left && !currentQ.left) ||
26+
(!currentP.left && currentQ.left)
27+
) {
28+
return false;
29+
}
30+
31+
if (
32+
(currentP.right && !currentQ.right) ||
33+
(!currentP.right && currentQ.right)
34+
) {
35+
return false;
36+
}
37+
38+
if (currentP.left && currentQ.left) {
39+
if (!dfs(currentP.left, currentQ.left)) {
40+
return false;
41+
}
42+
}
43+
44+
if (currentP.right && currentQ.right) {
45+
if (!dfs(currentP.right, currentQ.right)) {
46+
return false;
47+
}
48+
}
49+
50+
return true;
51+
};
52+
53+
if ((p && !q) || (!p && q)) {
54+
return false;
55+
}
56+
57+
if (p && q) {
58+
return dfs(p, q);
59+
}
60+
61+
return true;
62+
};

0 commit comments

Comments
 (0)