DSA Patterns (Multi-Lang)•Part 7: Binary Trees, BSTs & Traversals (53 - 64)
Same Tree & Symmetric Tree.
In Simple Words:
- Same Tree:
p.val === q.valandisSame(p.left, q.left)andisSame(p.right, q.right). - Symmetric Tree: Compare mirror reflections
t1.val === t2.valandisMirror(t1.left, t2.right)andisMirror(t1.right, t2.left). - Time: $O(N)$ | Space: $O(H)$
Multi-Language SolutionsPython 3 • JavaScript • TypeScript • Java • C++
Switch tabs or choose Alldef isSameTree(p: TreeNode | None, q: TreeNode | None) -> bool:
if not p and not q: return True
if not p or not q or p.val != q.val: return False
return isSameTree(p.left, q.left) and isSameTree(p.right, q.right)
def isSymmetric(root: TreeNode | None) -> bool:
def mirror(t1, t2):
if not t1 and not t2: return True
if not t1 or not t2 or t1.val != t2.val: return False
return mirror(t1.left, t2.right) and mirror(t1.right, t2.left)
return mirror(root.left, root.right) if root else True