-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathsymmetrical-tree.js
49 lines (44 loc) · 1.29 KB
/
symmetrical-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
// This is an input class. Do not edit.
class BinaryTree {
constructor(value) {
this.value = value;
this.left = null;
this.right = null;
}
}
// Time O(n)
// Space O(h) - where h is the height of the tree
function symmetricalTree(tree) {
if (tree === null) return false;
if (tree.left === null && tree.right === null) return true;
const leftStack = [tree.left];
const rightStack = [tree.right];
while (leftStack.length > 0) {
const left = leftStack.pop();
const right = rightStack.pop();
if (left === null && right === null) continue;
if (left === null && right !== null) return false;
if (left !== null && right === null) return false;
if (left.value !== right.value) return false;
leftStack.push(left.left);
rightStack.push(right.right);
leftStack.push(left.right);
rightStack.push(right.left);
}
return true;
}
// recursive solution
function symmetricalTree(tree) {
return checkSymmetrical(tree.left, tree.right);
}
// Time O(n)
// Space O(h) - where h is the height of the tree
function checkSymmetrical(left, right) {
if (left !== null && right !== null && left.value === right.value) {
return (
checkSymmetrical(left.left, right.right) &&
checkSymmetrical(left.right, right.left)
);
}
return left === right;
}