-
Notifications
You must be signed in to change notification settings - Fork 125
/
Copy pathJeehay28.js
69 lines (54 loc) ยท 1.82 KB
/
Jeehay28.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
// ๐ Iterative DFS (Stack)
// โ
Time Complexity: O(n), where n is the number of nodes in the tree
// โ
Space Complexity: O(n) (worst case), O(log n) (best case for balanced trees)
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} p
* @param {TreeNode} q
* @return {boolean}
*/
var isSameTree = function (p, q) {
let stack = [[p, q]];
while (stack.length > 0) {
const [p, q] = stack.pop();
if (p === null && q === null) continue;
if (p === null || q === null) return false;
if (p.val !== q.val) return false;
stack.push([p.left, q.left]);
stack.push([p.right, q.right]);
}
return true;
};
// ๐ recursive approach
// โ
Time Complexity: O(n), where n is the number of nodes in the tree
// โ
Space Complexity: O(n) (worst case), O(log n) (best case for balanced trees)
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} p
* @param {TreeNode} q
* @return {boolean}
*/
// var isSameTree = function (p, q) {
// // Base case: If both trees are empty, they are the same
// if (p === null && q === null) return true;
// // If one of the trees is empty and the other is not, return false
// if (p === null || q === null) return false;
// // Compare the values of the current nodes
// if (p.val !== q.val) return false;
// // Recursively compare the left and right subtrees
// return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
// };