Check if a binary tree is subtree of another binary tree | Set 1
Given two binary trees, check if the first tree is subtree of the second one. A subtree of a tree T is a tree S consisting of a node in T and all of its descendants in T. The subtree corresponding to the root node is the entire tree; the subtree corresponding to any other node is called a proper subtree.
For example, in the following case, tree S is a subtree of tree T.
Tree 2 10 / \ 4 6 \ 30
Become a success story instead of just reading about them. Prepare for coding interviews at Amazon and other top product-based companies with our Amazon Test Series. Includes topic-wise practice questions on all important DSA topics along with 10 practice contests of 2 hours each. Designed by industry experts that will surely help you practice and sharpen your programming skills. Wait no more, start your preparation today!
Tree 1 26 / \ 10 3 / \ \ 4 6 3 \ 30
Solution: Traverse the tree T in preorder fashion. For every visited node in the traversal, see if the subtree rooted with this node is identical to S.
Following is the implementation for this.
Tree 2 is subtree of Tree 1
Time Complexity: Time worst-case complexity of above solution is O(mn) where m and n are number of nodes in given two trees.
Auxiliary space: O(n)
We can solve the above problem in O(n) time. Please refer Check if a binary tree is subtree of another binary tree | Set 2 for O(n) solution.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.