Home > Reflections | ⏮️ ⏭️

2024-07-08

🏋 Coding Practice

Today I’ll implement the more direct recursive solution discussed yesterday.

101. Symmetric Tree

Given the root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center).

🪞 Reflections

  1. This is a shorter and more direct solution that what I came up with on my own.
  2. While I didn’t time it, this only took a few minutes to implement.
  3. It may be another nice exercise to mechanically translate this unusual recursive function into an iterative function.

⌨️ The Solution

function areMirrors(t1: TreeNode | null, t2: TreeNode | null): boolean {  
  if (!t1 && !t2) return true  
  if (!t1 || !t2) return false  
  if (t1.val !== t2.val) return false  
  return areMirrors(t1.left, t2.right) && areMirrors(t1.right, t2.left)  
}  
  
function isSymmetric(root: TreeNode | null): boolean {  
  return areMirrors(root, root)  
}