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 is subtree of another binary tree | Set 2
- Check if the given Binary Tree have a Subtree with equal no of 1's and 0's
- Check whether a binary tree is a full binary tree or not | Iterative Approach
- Subtree with given sum in a Binary Tree
- Find the largest BST subtree in a given Binary Tree | Set 1
- Find the largest Perfect Subtree in a given Binary Tree
- 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
- Check whether a binary tree is a full binary tree or not
- Check whether a given binary tree is skewed binary tree or not?
- Change a Binary Tree so that every node stores sum of all nodes in left subtree
- Given level order traversal of a Binary Tree, check if the Tree is a Min-Heap
- Check whether a binary tree is a complete tree or not | Set 2 (Recursive Solution)
- Check if a given Binary Tree is height balanced like a Red-Black Tree
- Complexity of different operations in Binary tree, Binary Search Tree and AVL tree