LeetCode: Symmetric Tree Solution

Recursion

Approach

Base cases:

  • false
    when either left or right is null
  • true
    when both left and right are null
  • false
    when both values of left and right are not equal

Implementation

1var isSymmetric = function (root) {
2 if (!root) return true
3
4 const recursion = (left, right) => {
5 if ((!left && right) || (left && !right)) return false
6 if (!left && !right) return true
7 if (left.val !== right.val) return false
8 return (
9 recursion(left.left, right.right) && recursion(left.right, right.left)
10 )
11 }
12
13 return recursion(root.left, root.right)
14}

References

Original problem

Comments

Loading comments...

Tags

leetcode

tree

binary tree

recursion

Next Post

LeetCode: Word Pattern

Oct 4, 2022

2 hash tables

Previous Post

LeetCode: Implement Queue using Stacks

Sep 30, 2022

Code speaks for itself

HoningJS

Search Posts