I have two binary trees T1
and T2
, and they are both character trees, which means:
struct TreeNode
{
char data;
TreeNode* left;
TreeNode* right;
TreeNode(const char d, TreeNode* const lptr = NULL,
TreeNode* const rptr = NULL)
: data(d), left(lptr), right(rptr){}
};
If PreOrder2
is a substring of PreOrder1
, and InOrder2
is a substring of InOrder1
, then T2
is a subtree of T1
.
Is the above statement true?
Definition of Tree Equal: if T1
and T2
have the exactly same data values AND distribution, then T1 == T2
, otherwise T1 != T2
(NULL trees are equal).
Definition of SubTree: if there is at least one node N1
in T1
that N1 == T2
, then T2
is a subtree of T1
.
Basically, I am NOT talking about the equivalence of the node addresses; I am talking about the data values and distribution of the tree.
== EDIT ==
I think it's not true. It's possible that there are two subtrees in T1
, one of which has the same PreOrder as T2
, the other has the same InOrder as T2
.
Now my question becomes: is there a simple way to determine if T2
is a subtree of T1
using traversals?
== EDIT ==
A typical example to make the statement to false:
T1:
A
B C
C B
D D
T2:
B
C D
Another T1:
A
A A
B B C
C D B
D C D
I've been looking for an algorithm which checks if T2 is a subtree of T1 that takes less than O(m*n).
After some searching I found these two threads:
Determine if a binary tree is subtree of another binary tree using pre-order and in-order strings
checking subtrees using preorder and inorder strings
Looking at these it may actually be possible to find a subtree using only preorder and inorder strings. Interestingly, they were also talking about the conflicting definitions of subtrees.
Anyways, I've yet to test this method myself but how about you try this?:
Flatten the trees T1 and T2 into strings (like we talked about in chat) in both preorder and inorder traversal, but this time include every NULL leaves in the string as well (for example as a whitespaces) and then try to check for a substring.