forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0100-same-tree.js
71 lines (55 loc) · 1.49 KB
/
0100-same-tree.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
68
69
70
71
/**
* https://leetcode.com/problems/same-tree/
* TIme O(N) | Space O(H)
* @param {TreeNode} p
* @param {TreeNode} q
* @return {boolean}
*/
var isSameTree = function(p, q) {
const isBaseCase = !(p || q);
if (isBaseCase) return true;
const isBalanced = (p && q);
if (!isBalanced) return false;
const isSame = p.val === q.val;
if (!isSame) return false;
return dfs(p, q);
};
const dfs = (p, q) => {
const left = isSameTree(p.left, q.left);
const right = isSameTree(p.right, q.right);
return left && right;
}
/**
* https://leetcode.com/problems/same-tree/
* TIme O(N) | Space O(W)
* @param {TreeNode} p
* @param {TreeNode} q
* @return {boolean}
*/
var isSameTree = function(p, q) {
if (isSameNode(p, q)) return true;
return bfs([[ p, q ]]);
}
const bfs = (queue) => {
while (queue.length) {
for (let i = (queue.length - 1); 0 <= i; i--) {
const [ p, q ] = queue.shift();
if (!isSame(p, q)) return false;
if (p.left) queue.push([ p.left, q.left ]);
if (p.right) queue.push([ p.right, q.right ]);
}
}
return true;
}
const isSameNode = (p, q) => {
const isBaseCase = !(p || q);
if (isBaseCase) return true;
const isBalanced = (p && q);
if (!isBalanced) return false;
const isSame = p.val === q.val;
if (!isSame) return false;
return true;
}
const isSame = (p, q) => isSameNode(p, q)
&& isSameNode(p.left, q.left)
&& isSameNode(p.right, q.right);