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
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.
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.
- Check if a Binary Tree contains duplicate subtrees of size 2 or more
- Serialize and Deserialize a Binary Tree
- Check if a binary tree is subtree of another binary tree | Set 2
- Find the maximum path sum between two leaves of a binary tree
- Populate Inorder Successor for all nodes
- Connect nodes at same level using constant extra space
- Connect nodes at same level
- Check if a given Binary Tree is SumTree
- Print Ancestors of a given node in Binary Tree
- Get Level of a node in a Binary Tree
- Print nodes at k distance from root
- Construct Tree from given Inorder and Preorder traversals
- If you are given two traversal sequences, can you construct the binary tree?
- Write Code to Determine if Two Trees are Identical
- Tree Traversals (Inorder, Preorder and Postorder)
Improved By : SrivathsanAravamudan