101. Symmetric Tree
Description
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.
Solution
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {boolean}
*/
var isSymmetric = function(root) {
"use strict";
if (!root) {
return true;
}
function check(node1, node2) {
if (!node1 || !node2) {
return node1 === node2;
}
if (node1.val === node2.val) {
if (check(node1.left, node2.right) &&
check(node1.right, node2.left)) {
return true;
}
}
return false;
}
return check(root.left, root.right);
};