-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathisSymmetric.js
31 lines (30 loc) · 945 Bytes
/
isSymmetric.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
//+ Jonas Raoni Soares Silva
//@ http://raoni.org
/**
* 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} root
* @return {boolean}
*/
var isSymmetric = function(root) {
function *navigate(node, first, second){
for (const stack = [node]; stack.length;) {
if ((yield node = stack.pop()))
stack.push(node[first], node[second]);
}
}
// Navigate through left/right sides, in a kind of mirrored way
const left = navigate(root?.left, "left", "right"), right = navigate(root?.right, "right", "left");
for (const node of left) {
// The value must be always equal
if (node?.val !== right.next().value?.val)
return false;
}
return true;
};