Solution: Symmetric Tree
Let's solve the Symmetric Tree problem using the Tree BFS pattern.
We'll cover the following
Statement#
Given the root of a binary tree, check whether it is a symmetric tree. A symmetric tree refers to a tree that is the mirror of itself, i.e., symmetric around its root.
Constraints:
- The tree contains nodes in the range .
-
Node.data
Solution#
Starting from the root, we have to check that the left and right subtrees of the tree are mirrors of each other. The tree containing a single element root is always symmetric; we will return TRUE in this case. Otherwise, we will use the following algorithm:
- We take a queue with
root's right and left nodes. - Iterate a loop till the queue is not empty.
- In each iteration, we dequeue two elements from the queue and store them in two variables,
leftandright.- If both
leftandrightare NULL, it means that the node doesn’t have any child. So, we move to the next interaction. - If any from
leftandrightis NULL, it means that either the left child or right child of the node doesn’t exist, which leads us to the conclusion that the tree is not symmetric; we return FALSE. - If the values of
leftandrightare different, it also means that the tree is not symmetric; we return FALSE.
- If both
- Then, we append the left node of
left, the right node ofright, the left node ofright, and the right node ofleftin the queue in the same order, and we move to the next interaction. - After completing all interactions, if the algorithm is not returned from any step, this indicates that the tree is symmetric, so we return TRUE.
Let’s look at the following illustration to get a better understanding of the solution:
1 of 10
2 of 10
3 of 10
4 of 10
5 of 10
6 of 10
7 of 10
8 of 10
9 of 10
10 of 10
Let’s have a look at the code for the algorithm we just discussed.
Note: This can also be achieved using a stack instead of a queue.
Time complexity#
The time complexity of this solution is , where is the total number of nodes in the tree. This is because we traverse the entire tree once.
Space complexity#
Additional space is required to store a maximum of elements in the queue, where is the total number of nodes in the tree. So, the space complexity of this solution is .
Symmetric Tree
Vertical Order Traversal of a Binary Tree