Given two binary trees, check whether the leaf traversals of both trees are the same or not.

For example, the leaf traversals of the following binary trees are 4, 5, 6.


Leaf Traversal of Binary Tree

A simple solution is to traverse the first tree using inorder traversal and store each encountered leaf in an array. Repeat the same for the second BST. Then the problem reduces to comparing two arrays for equality. The time complexity of this approach is O(m + n), and the additional space used is O(m + n). Here m is the total number of nodes in the first tree, and n is the total number of nodes in the second tree.

The idea is to traverse both trees simultaneously using the iterative preorder traversal and compare data of each encountered leaf node, i.e., the i'th leaf in the first tree is compared with the i'th leaf in the second tree. The algorithm can be implemented as follows in C++, Java, and Python:

C++

Download   Run Code

Output:

The tree traversals are the same

Java

Download   Run Code

Output:

The tree traversals are the same

Python

Download   Run Code

Output:

The tree traversals are the same

Download   Run Code
Output:

The tree traversals are the same

Download   Run Code
Output:

The tree traversals are the same

Download   Run Code
Output:

The tree traversals are the same

The time complexity of the above solution is O(m + n), where m is the total number of nodes in the first tree and n is the total number of nodes in the second tree. Extra space of O(x + y) is used for the stack data structure where x is the height of the first tree, and y is the height of the second tree.

Another approach is to connect leaf nodes in the form of a linked list and then traverse both lists and compare their data. Following is the C++, Java, and Python program that demonstrates it:

C++

Download   Run Code

Output:

The tree traversals are the same

Java

Download   Run Code

Output:

The tree traversals are the same

Python

Download   Run Code

Output:

The tree traversals are the same

Download   Run Code
Output:



The tree traversals are the same

Download   Run Code
Output:

The tree traversals are the same

Download   Run Code
Output:

The tree traversals are the same

source