Prepin
Log in

Verify whether the two specified binary trees are the same or not.

Approach / Explanation

This question requires you to determine whether two binary trees are the same. This means that their structure and the values in their nodes must be identical. Key points to remember: For two binary trees to be identical, they must share the same root value. The left subtree of each tree must be the same. The right subtree of each tree must also be the same. To address this question, you can describe either a recursive or iterative approach that starts at the root of both trees, comparing their structures and node values one by one until you can establish whether the two trees are identical or not.

Suggested Answer

To address this issue, we will implement a recursive strategy. Here’s how to write this in Python: class Node : def __init__ ( self , data ) : self . data = data self . left = None self . right = None def is_identical ( node1 , node2 ) : if node1 is None and node2 is None : return True if node1 is not None and node2 is not None : return ( ( node1 . data == node2 . data ) and is_identical ( node1 . left , node2 . left ) and is_identical ( node1 . right , node2 . right ) ) return False In this method, we begin by checking if both root nodes are None . If they are, we return True since two None trees are considered identical. Next, we verify that both nodes are not None and then recursively assess their left and right children. If any corresponding nodes have different values, we return False .

Alternative Answer

Alternatively, we can tackle this problem using an iterative approach with a breadth-first search strategy in Python: from collections import deque def is_identical ( node1 , node2 ) : q = deque ( [ ( node1 , node2 ) ] ) while q : n1 , n2 = q . popleft ( ) if n1 is None and n2 is None : continue elif n1 is not None and n2 is not None : if n1 . data == n2 . data : q . append ( ( n1 . left , n2 . left ) ) q . append ( ( n1 . right , n2 . right ) ) else : return False else : return False return True This code enqueues pairs of nodes from the two binary trees if both nodes are not None and have equal values. The process continues until all node pairs have been enqueued and evaluated. If all corresponding node pairs from both trees have the same value throughout the traversal, then the two trees are considered identical. Otherwise, it returns False , indicating that the trees are not identical.

Question Details

Difficulty & Category

Medium
data structures

Product

For CandidatesFor RecruitersCompaniesBrowse JobsInterview QuestionsDeep ProfileSkill AssessmentOpportunity Matching
Prepin.ai

© 2026 Prepin LLC · Philadelphia, PA · All rights reserved.