micahbales

101. Symmetric Tree

Nov 3rd, 2023 (edited)
1,095
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /**
  2. * Problem statement: https://leetcode.com/problems/symmetric-tree/
  3. *
  4. * The first solution here is an iterative one. It's not as efficient or elegant as the recursive solution that follows.
  5. */
  6.  
  7. /* Iterative Solution */
  8.  
  9. function getNodesRight(node, stack) {
  10.     if (node === null) return [null]
  11.     return [...stack,
  12.             node.val,
  13.             ...getNodesRight(node.right, stack),
  14.             ...getNodesRight(node.left, stack)]
  15. }
  16.  
  17. function getNodesLeft(node, stack) {
  18.     if (node === null) return [null]
  19.     return [...stack,
  20.             node.val,
  21.             ...getNodesLeft(node.left, stack),
  22.             ...getNodesLeft(node.right, stack)]
  23. }
  24.  
  25.  /**
  26.  * @param {TreeNode} root
  27.  * @return {boolean}
  28.  */
  29. var isSymmetric = function(root) {
  30.     if (root === null) return true
  31.  
  32.     const leftNodes = getNodesLeft(root.left, [])
  33.     const rightNodes = getNodesRight(root.right, [])
  34.  
  35.     for (let i = 0; i < leftNodes.length; i++) {
  36.         if (leftNodes[i] !== rightNodes[i]) return false
  37.     }
  38.  
  39.     return true
  40. }
  41.  
  42.  
  43. /* Recursive Solution */
  44.  
  45. function isMirror(left, right) {
  46.     if (left === null && right == null) return true
  47.     if (left === null || right === null) return false
  48.     if (left.val !== right.val) return false
  49.     return isMirror(left.left, right.right) && isMirror(left.right, right.left)
  50. }
  51.  
  52.  /**
  53.  * @param {TreeNode} root
  54.  * @return {boolean}
  55.  */
  56. var isSymmetric = function(root) {
  57.     if (root === null) return true
  58.     return isMirror(root.left, root.right)
  59. }
Advertisement
Add Comment
Please, Sign In to add comment