Symmetric Tree
Master this topic with zero to advance depth.
Symmetric Tree
Check if a tree is a mirror of itself.
Examples
Level I: Recursive DFS
Intuition
A tree is symmetric if its left and right subtrees are mirrors of each other. Two trees t1 and t2 are mirrors if:
- Their roots have the same value.
t1.leftis a mirror oft2.right.t1.rightis a mirror oft2.left.
Detailed Dry Run
Mirror(L, R) -> L.val == R.val && Mirror(L.left, R.right) && Mirror(L.right, R.left).
Level II: Iterative BFS (Queue)
Intuition
Use a queue to process nodes in pairs. Each pair contains nodes that should be mirrors of each other. For a root, we push (root.left, root.right).
Diagram
(1) Queue: [1.L, 1.R] -> [2, 2]
(2) Pop pair (2, 2), Push pairs: [(2.L, 2.R), (2.R, 2.L)] -> [3, 3, 4, 4]Detailed Dry Run
Queue: [2, 2]. Pop 2, 2. Push 3(L), 3(R) and 4(R), 4(L). Queue: [3, 3, 4, 4]. All match -> true.
Level III: Iterative DFS (Two Stacks)
Intuition
Process the tree in parallel using two stacks. One stack follows Left -> Right and the other follows Right -> Left. Their values and structure must match at every step.
Detailed Dry Run
Stack1: [L], Stack2: [R]. Pop both, compare. Push L1.left, R1.right and L1.right, R1.left to respective stacks.
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.