Symmetric Tree
Expert Answer & Key Takeaways
A complete guide to understanding and implementing Trees.
Symmetric Tree
Check if a tree is a mirror of itself.
Examples
Input: root = [1,2,2,3,4,4,3]
Output: true
Approach 1
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.
⏱ O(N)💾 O(H)
Detailed Dry Run
Mirror(L, R) -> L.val == R.val && Mirror(L.left, R.right) && Mirror(L.right, R.left).
Approach 2
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]⏱ O(N)💾 O(W)
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.
Approach 3
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.⏱ O(N)💾 O(H)
Detailed Dry Run
Stack1: [L], Stack2: [R]. Pop both, compare. Push L1.left, R1.right and L1.right, R1.left to respective stacks.
Course4All Technical Board
Verified ExpertSenior Software Engineers & Algorithmic Experts
Our DSA content is authored and reviewed by engineers from top tech firms to ensure optimal time and space complexity analysis.
Pattern: 2026 Ready
Updated: Weekly
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.