Problem
Given two binary trees check if they are mirror image of each other.
Examples
Example 1:
graph LR subgraph Original A(1) --- B(2) & C(3) B --- D(4) B ~~~ N1:::hidden C ~~~ N2:::hidden C --- E(5) end subgraph Mirror A1(1) --- C1(3) & B1(2) C1 --- E1(5) C1 ~~~ N3:::hidden B1 ~~~ N4:::hidden B1 --- D1(4) end Original --> Mirror classDef hidden display:none
|
|
Example 2:
|
|
Solution
Method 1 - Using Preorder
Do the preorder traversal on both the trees simultaneously. if any node doesn’t have corresponding node in the another tree, return false. check if left node in one tree is the right node in another tree, and vice verse.
To check if two binary trees are mirror images:
- Compare the root nodes of each tree. They must be equal.
- Recursively check that:
- The left subtree of the first tree is a mirror to the right subtree of the second tree.
- The right subtree of the first tree is a mirror to the left subtree of the second tree.
If these conditions hold true for all nodes recursively, the trees are mirror images of each other.
Approach
- Base Case:
- If both nodes are
null
, returntrue
(they are mirrors at this point). - If one node is
null
while the other isn’t, returnfalse
.
- If both nodes are
- Recursive Case:
- Compare the values of the current nodes of both trees.
- Recursively check:
- The left subtree of the first tree is the mirror of the right subtree of the second.
- The right subtree of the first tree is the mirror of the left subtree of the second.
- Return the result of recursive checks.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n)
wheren
is the number of nodes in the larger of the two trees. We need to visit every node once. - 🧺 Space complexity:
O(h)
whereh
is the height of the larger tree. This is due to the recursive call stack.