Updated on January 27, 2019
Symmetric tree
5
3
3
1
1
Problem
Given a binary tree (not necessarily a binary search tree), check if the tree is symmetric. A tree is symmetric if the nodes on the left mirror the nodes on the right. A tree is asymmetric if it is not symmetric.
Input
tree
- A tree node consisting of a value, and left/right children.
Approach
We can approach the solution in two steps:
- Copy the tree and swap the left and right nodes with each other at each level
- Compare the original tree and the mirrored tree by traversing down both trees simultaneously.
The second step is also not too shabby.
Now, all we need to do is copy the original tree and mirrorize the tree, then compare the two trees.
Optimization
We can save some space complexity by skipping the copying of the original tree.
In a similar light to equals_tree(tree1, tree2)
, we can examine two trees and check for a couple things that make a tree symmetric.
Black = NULL Nodes, Yellow = Mirrored Nodes
5
3
3
nil
1
1
nil
Cases for symmetry:
- If and is both
null
, then we can say its symmetric because they are equivalent. (See black nodes) - If the left node of is the same as the right node of and the left node of is the same as the right node of , then we can say its symmetric. (i.e. the two 3 nodes)
All other cases must mean that the original tree is asymmetric because and are not mirrored.