Check If Two Binary Trees are Identical (Same Tree)

How to Check If Two Binary Trees are Identical.

Given two binary trees, write a code to check if they are the same or not.

Two binary trees are considered the same if they are structurally identical and the nodes have the same value.

For example: (Check the image)

Example 1: true

In this first example, Both the trees are same. They have the same structure as well as their node values are same.

Example 2: false

In the second example, Both the trees are structurally same but the value of left children of tree A is not equal to tree B.

Example 3: false

Both the trees are structurally not identical.

Check If Two Binary Trees are Identical

In this tutorial, I am going to discuss iterative and recursive approach to solve this problem. At the end of this post i have shared a video tutorial link in which i have explained both the approaches.

Programming questions on binary trees

Programming Video Tutorials

Check If Two Binary Trees are Identical using Level Order Traversal – Java Code

In this example, we are going to solve this problem using Level Order Traversal. We traverse both the trees level by level simultaneously and compare the nodes value.

If both the trees are same then it means both have same structure as well as their node values are same.

The time and space complexity of this approach is O(n).

Check If Two Trees are Identical using Recursion – Java Code

In the last example, we have solved this problem using iterative approach. Let’s see how we can solve this problem using recursion.

To solve this problem using recursion, we have to check these three conditions in each recursive call.

i) If both the trees are empty then return true.

ii) Else if any of the tree is empty and other is not then return false.

iii) Else if data of both the nodes are not same then return false.

The time complexity of this approach is O(n).

Tagged . Bookmark the permalink.

About WebRewrite

I am technology lover who loves to keep updated with latest technology. My interest field is Web Development.