There are two binary trees T1 and T2 which store character data, duplicates allowed.
How can I find whether T2 is a subtree of T1 ? .
T1 has millions of nodes and
Let us say we have T1 as parent tree and T2 as a tree which might be a subtree of T1. Do the following. Assumption made is T1 and T2 are binary tree without any balancing factor.
1) Search the root of T2 in T1. If not found T2 is not a subtree. Searching the element in BT will take O(n) time.
2) If the element is found, do pre-order traversal of T1 from the node root element of T2 is found. This will take o(n) time. Do pre-order traversal of T2 as well. Will take O(n) time. Result of pre-order traversal can be stored into a stack. Insertion in stack will take only O(1).
3) If size of two stacks is not equal, T2 is not a subtree.
4) Pop one element from each stack and check for equality. If mismatch occurs, T2 is not a subtree.
5) If all elments matched T2 is a subtree.