Skip to content

Commit 8d147e4

Browse files
committed
add 100 leetcode easy
1 parent 5df07d9 commit 8d147e4

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

binary-trees/100-same-tree.js

+41
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* function TreeNode(val, left, right) {
4+
* this.val = (val===undefined ? 0 : val)
5+
* this.left = (left===undefined ? null : left)
6+
* this.right = (right===undefined ? null : right)
7+
* }
8+
*/
9+
/**
10+
* @param {TreeNode} p
11+
* @param {TreeNode} q
12+
* @return {boolean}
13+
* Time O(N)
14+
* Space O(N)
15+
* Both solutions run in the same time-space complexity
16+
*/
17+
18+
// iterative solution
19+
var isSameTree = function (p, q) {
20+
const stack = [[p, q]];
21+
22+
while (stack.length > 0) {
23+
const [p, q] = stack.pop();
24+
25+
if (p === null && q === null) continue;
26+
if (p === null || q === null) return false;
27+
if (p.val !== q.val) return false;
28+
stack.push([p.left, q.left]);
29+
stack.push([p.right, q.right]);
30+
}
31+
return true;
32+
};
33+
34+
// recursive solution
35+
// function isSameHelper(tree1, tree2) {
36+
// if (tree1 === null && tree2 === null) return true;
37+
// if (tree2 === null || tree2 === null) return false;
38+
// if (tree1.val !== tree2.val) return false;
39+
40+
// return isSameHelper(tree1.left, tree2.left) && isSameHelper(tree1.right, tree2.right);
41+
// }

0 commit comments

Comments
 (0)