-
Notifications
You must be signed in to change notification settings - Fork 156
/
Copy pathsymmetric-tree.js
119 lines (97 loc) · 2.1 KB
/
symmetric-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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
/**
* Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
*
* For example, this binary tree [1,2,2,3,4,4,3] is symmetric:
*
* 1
* / \
* 2 2
* / \ / \
* 3 4 4 3
* But the following [1,2,2,null,3,null,3] is not:
* 1
* / \
* 2 2
* \ \
* 3 3
* Note:
* Bonus points if you could solve it both recursively and iteratively.
*/
/**
* Recursion Solution
*
* @param {TreeNode} root
* @return {boolean}
*/
const isSymmetric = root => {
if (!root) {
return true;
}
const isMirror = (p, q) => {
if (!p && !q) {
return true;
}
if (!p || !q) {
return false;
}
return isMirror(p.left, q.right) && isMirror(p.right, q.left);
};
return isMirror(root.left, root.right);
};
/**
* Preorder DFS Iterative Solution
*
* @param {TreeNode} root
* @return {boolean}
*/
const isSymmetricDFS = root => {
if (!root) {
return true;
}
const isMirror = (p, q) => {
const s1 = [p];
const s2 = [q];
while (s1.length > 0 || s2.length > 0) {
const n1 = s1.pop();
const n2 = s2.pop();
// Two null nodes, let's continue
if (!n1 && !n2) continue;
// Return false as long as there is a mismatch
if (!n1 || !n2 || n1.val !== n2.val) return false;
s1.push(n1.left);
s1.push(n1.right);
s2.push(n2.right);
s2.push(n2.left);
}
return true;
};
return isMirror(root.left, root.right);
};
/**
* BFS Iterative Solution
*
* @param {TreeNode} root
* @return {boolean}
*/
const isSymmetricBFS = root => {
if (!root) {
return true;
}
const isMirror = (s, t) => {
const q1 = [s];
const q2 = [t];
while (q1.length > 0 || q2.length > 0) {
const n1 = q1.shift();
const n2 = q2.shift();
if (!n1 && !n2) continue;
if (!n1 || !n2 || n1.val !== n2.val) return false;
q1.push(n1.left);
q1.push(n1.right);
q2.push(n2.right);
q2.push(n2.left);
}
return true;
};
return isMirror(root.left, root.right);
};
export { isSymmetric, isSymmetricDFS, isSymmetricBFS };