Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Problem statement: https://leetcode.com/problems/symmetric-tree/
- *
- * The first solution here is an iterative one. It's not as efficient or elegant as the recursive solution that follows.
- */
- /* Iterative Solution */
- function getNodesRight(node, stack) {
- if (node === null) return [null]
- return [...stack,
- node.val,
- ...getNodesRight(node.right, stack),
- ...getNodesRight(node.left, stack)]
- }
- function getNodesLeft(node, stack) {
- if (node === null) return [null]
- return [...stack,
- node.val,
- ...getNodesLeft(node.left, stack),
- ...getNodesLeft(node.right, stack)]
- }
- /**
- * @param {TreeNode} root
- * @return {boolean}
- */
- var isSymmetric = function(root) {
- if (root === null) return true
- const leftNodes = getNodesLeft(root.left, [])
- const rightNodes = getNodesRight(root.right, [])
- for (let i = 0; i < leftNodes.length; i++) {
- if (leftNodes[i] !== rightNodes[i]) return false
- }
- return true
- }
- /* Recursive Solution */
- function isMirror(left, right) {
- if (left === null && right == null) return true
- if (left === null || right === null) return false
- if (left.val !== right.val) return false
- return isMirror(left.left, right.right) && isMirror(left.right, right.left)
- }
- /**
- * @param {TreeNode} root
- * @return {boolean}
- */
- var isSymmetric = function(root) {
- if (root === null) return true
- return isMirror(root.left, root.right)
- }
Advertisement
Add Comment
Please, Sign In to add comment