![]() |
VOOZH | about |
Given a binary tree, check whether it is a mirror of itself.
Examples:
Input: 5 / \ 3 3 / \ / \ 8 9 9 8 Output: Symmetric Input: 5 / \ 8 7 \ \ 4 3 Output: Not Symmetric
Approach: The idea is to traverse the tree using Morris Traversal and Reverse Morris Traversal to traverse the given binary tree and at each step check that the data of the current node is equal in both the traversals. If at any step the data of the nodes are different. Then, the given tree is not Symmetric Binary Tree.
Below is the implementation of the above approach:
Output:
Symmetric
Time Complexity: Since every edge of the tree is traversed at most two times exactly as in the case of Morris traversal and in the worst case, the same number of extra edges (as input tree) are created and removed. Therefore, the time complexity of this approach is O(N).
Auxiliary Space: O(1)