InterviewHubPRO
Section Overview
Q57

Question 57 of 100

Part 7: Binary Trees, BSTs & Traversals (53 - 64)

57%
DSA Patterns (Multi-Lang)•Part 7: Binary Trees, BSTs & Traversals (53 - 64)

Same Tree & Symmetric Tree.

In Simple Words:

  • Same Tree: p.val === q.val and isSame(p.left, q.left) and isSame(p.right, q.right).
  • Symmetric Tree: Compare mirror reflections t1.val === t2.val and isMirror(t1.left, t2.right) and isMirror(t1.right, t2.left).
  • Time: $O(N)$ | Space: $O(H)$
Multi-Language Solutions
Switch tabs or choose All
def 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