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.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Check if a binary tree is subtree of another binary tree | Set 2
- Check if a binary tree is subtree of another binary tree using preorder traversal : Iterative
- Check if the given Binary Tree have a Subtree with equal no of 1's and 0's
- Find the largest BST subtree in a given Binary Tree | Set 1
- Duplicate subtree in Binary Tree | SET 2
- Subtree with given sum in a Binary Tree
- Change a Binary Tree so that every node stores sum of all nodes in left subtree
- Find the largest Complete Subtree in a given Binary Tree
- Convert a Binary Tree such that every node stores the sum of all nodes in its right subtree
- Find the largest Perfect Subtree in a given Binary Tree
- Check if two nodes are in same subtree of the root node
- Even size subtree in n-ary tree
- Subtree of all nodes in a tree using DFS
- Euler Tour | Subtree Sum using Segment Tree
- Find largest subtree sum in a tree
- Queries for DFS of a subtree in a tree
- Number of leaf nodes in the subtree of every node of an n-ary tree
- Find the Kth node in the DFS traversal of a given subtree in a Tree
- Count of distinct colors in a subtree of a Colored Tree with given min frequency for Q queries
- Find GCD of each subtree of a given node in an N-ary Tree for Q queries