Symmetric Tree

Try to solve the Symmetric Tree problem.

Statement#

Given the root of a binary tree, check whether it is a symmetric tree. A symmetric tree refers to a tree that is a mirror of itself, i.e., symmetric around its root.

Constraints:

  • The tree contains nodes in the range [1,500][1, 500].
  • 103-10^3 \le Node.data 103\le 10^3

Examples#

Created with Fabric.js 3.6.6 Sample example 1 Input 1 2 2 3 4 4 3 Output: TRUE

1 of 2

Created with Fabric.js 3.6.6 Input Sample example 2 18 21 21 47 20 21 47 Output: FALSE

2 of 2

Understand the problem#

Let’s take a moment to make sure you’ve correctly understood the problem. The quiz below helps you check if you’re solving the correct problem:

Symmetric Tree

1

What will be the output if the following tree is given as input?

tree = [25, 4, 67, 2, 3, 3, 2]

          __ 25 __ 
         |        |
       _ 4 _    _ 67 _ 
      |     |  |      |
      2     3  3      2 
       
A)

TRUE

B)

FALSE

Question 1 of 30 attempted

Figure it out!#

We have a game for you to play. Rearrange the logical building blocks to develop a clearer understanding of how to solve this problem.

Drag and drop the cards to rearrange them in the correct sequence.

Start traversing the tree from root node. Enqueue root’s left and right nodes in a queue.

In a loop, dequeue two elements and store in left and right.

If left and right are NULL, continue traversing and dequeue the next elements.

If any one from left and right is NULL, return FALSE.

If the value of left is not equal to the value of right, return FALSE.

Enqueue left node of the left, right node of the right, right node of the left, and left node of the right in queue.

The loop terminates when the queue is empty; return TRUE.


Try it yourself#

Implement your solution in the following coding playground.

Python
usercode > main.py
Input #1
%0 node_1 1 node_2 2 node_1->node_2 node_3 2 node_1->node_3 node_4 3 node_2->node_4 node_5 4 node_2->node_5 node_6 4 node_3->node_6 node_7 3 node_3->node_7
Visualization for Input #1
Symmetric Tree

Tree Breadth-first Search: Introduction

Solution: Symmetric Tree