Created
December 12, 2018 02:57
-
-
Save trevor-atlas/5003aabe6a9501e2c83af66a31290ed4 to your computer and use it in GitHub Desktop.
Check a binary tree for symmetry
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Definition for a binary tree node. | |
* function TreeNode(val) { | |
* this.val = val; | |
* this.left = this.right = null; | |
* } | |
*/ | |
/** | |
* @param {TreeNode} root | |
* @return {boolean} | |
*/ | |
const isSymmetric = (root) => { | |
if (root == null) { | |
return true; | |
} | |
return isMirrored(root.left, root.right) | |
}; | |
const isMirrored = (left, right) => { | |
if (left == null && right == null) { | |
return true; | |
} | |
if (left == null || right == null) { | |
return false; | |
} | |
if (left.val != right.val) { | |
return false; | |
} | |
return isMirrored(left.left, right.right) && isMirrored(left.right, right.left); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment