Skip to main content

Leetcode - 101. Symmetric Tree

· One min read

https://leetcode.com/problems/symmetric-tree/

Solution 1

/**
* 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) {
return root === null || isMirrorValue(root.left, root.right);
};

const isMirrorValue = (left, right) => {
if (left === null && right === null) {
return true;
}
if (left === null || right === null) {
return false;
}

if (left.val === right.val) {
return (
isMirrorValue(left.right, right.left) &&
isMirrorValue(left.left, right.right)
);
} else {
return false;
}
};