101. Symmetric Tree | JS
Intuition\n Describe your first thoughts on how to solve this problem. \n- At first i was thinking to solve it with iterative approach, but it would be costly t
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n- At first i was thinking to solve it with iterative approach, but it would be costly to use a queue for this, so i thought to use the recursive approach.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- We use recursive approach to solve this problem, the tree would be symmetric if it\'s foldable you know, so we should start by checking first if the root is null so we have a symmetric tree.\n\n- A tree would only be foldable - symmetric - if the left sub-tree leftNode is equivalent to the right sub-tree rightNode and left sub-tree rightNode is equivalent to right sub-tree leftNode.\n- so we build isMirror function that takes two nodes the left sub-tree parent and the right sub-tree parent and start the comparison as mentioned above in the second point.\n- If there is any failure for any tested condition the function will be terminated and return false so we don\'t have to check any more, that\'s because we are processing the tree level by level, so that\'s why we will be using o(h) where is h is the height of the tree at worst case.\n# Complexity\n- Time complexity: O(n) where is n is the nodes number because we check every single node.\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(h) where is h is the tree height.\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n/**\n * Definition for a binary tree node.\n * function TreeNode(val, left, right) {\n *     this.val = (val===undefined ? 0 : val)\n *     this.left = (left===undefined ? null : left)\n *     this.right = (right===undefined ? null : right)\n * }\n */\n/**\n * @param {TreeNode} root\n * @return {boolean}\n */\nvar isSymmetric = function(root) {\n    if(root == null) return true;\n    return isMirror(root.left, root.right);\n}; \n\nconst isMirror = (leftNode, rightNode) => {\n    if(leftNode == null && rightNode == null) return true;\n    if(leftNode == null || rightNode == null) return false;\n    if(leftNode.val !== rightNode.val) return false;\n   \n    return isMirror(leftNode.left, rightNode.right) && isMirror(leftNode.right, rightNode.left);\n}\n\n\n\n\n\n\n```
['Tree', 'Recursion', 'Binary Tree', 'JavaScript']