Check if a Binary Tree is subtree of another binary tree | Set 1
Given two binary trees, check if the first tree is a 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.
/ \ \
4 6 3
Output: S is subtree of tree T
The idea is to check at every node for the subtree.
Follow the steps below to solve the problem:
- 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.
- To check the subtree is identical or not traverse on the tree S and T simultaneously
- If a visited node is not equal then return false else continue traversing the whole tree S is traversed
Below is the implementation of above approach:
Tree 2 is subtree of Tree 1
Time Complexity: O(M*N), Traversing on subtree S of size M for every N node of Tree T.
Auxiliary space: O(n)
The above problem can be solved 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 if you want to share more information about the topic discussed above.
Please Login to comment...