Problem
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree [1,2,2,3,4,4,3]
is symmetric:
1 |
|
But the following [1,2,2,null,3,null,3]
is not:
1 |
|
Note: Bonus points if you could solve it both recursively and iteratively.
Explanation 1
-
In recursive method, from the above example, we don’t need to check the root node first. We can think of comparing the
root.left
subtree androot.right
subtree are symmetric. We need to meet three conditions if they are symmetric.- Left and right subtree’s root value are equal (2 == 2)
- Left subtree’s left value is equal to right subtree’s right value (3 == 3)
- Left subtree’s right value is equal to right subtree’s left value (4 == 4)
-
We can recursivly call the above helper method to if left subtree’s left tree with right subtree’s right tree are symmertric, and also left subtree’s right tree with right subtree’s left tree are symmetric.
-
The base case is when both values are null, we return true; else we return false. If the values are not equal, we also return false.
Solution 1
1 |
|
Explanation 2
- In iterative method, we can use a stack to push left subtree’s left value then push rigth subtree’s right value (these 2 values a group), also push left subtree’s right value and then push right subtree’s left value (these 2 values as a group). Then, we pop a group’s two value and compare this group’s two values are equal or not.
Solution 2
1 |
|