Created
April 17, 2022 09:54
-
-
Save esase/572a8a97b695e213295f515f90db91d1 to your computer and use it in GitHub Desktop.
Symmetric tree [https://leetcode.com/problems/symmetric-tree]
This file contains 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, 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) { | |
const leftValues = []; | |
const rightValues = []; | |
getValues(root.left, leftValues, true); | |
getValues(root.right, rightValues, false); | |
if (leftValues.length !== rightValues.length) { | |
return false; | |
} | |
for (i = 0; i < leftValues.length; i++) { | |
if (leftValues[i] !== rightValues[i]) { | |
return false; | |
} | |
} | |
return true; | |
}; | |
var getValues = function(node, values, isLeftDirection) { | |
if (!node) { | |
values.push(null); | |
return; | |
} | |
values.push(node.val); | |
if (isLeftDirection) { | |
getValues(node.left, values, isLeftDirection); | |
getValues(node.right, values, isLeftDirection); | |
return; | |
} | |
getValues(node.right, values, isLeftDirection); | |
getValues(node.left, values, isLeftDirection); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment