0

I have 2 binary trees, and the value of nodes are not necessary distinct. I want to determine if one tree is a subtree of another.

Is comparing the strings of the pre-order traversal of 2 trees with null nodes sufficient and necessary (iff condition) to determine if a tree is a subtree of another?

For example,

A.left = B

Pre-order: A, B, null, null, null

A.right = B

Pre-order: A, null, B, null, null

Cheng
  • 770
  • 11
  • 22
  • No. Consider the tree `A -> B -> C`. It's a subtree of `A -> B -> C`, but not of `A <- C -> B`, even though they have the same preorder traversal. – Oliver Charlesworth Sep 28 '14 at 22:29
  • Even simpler: `A.left = B` and `A.right = B`. This smells like homework. Don't forget to give credit to SO in order to avoid violating your school's academic honesty policy. – Raymond Chen Sep 28 '14 at 22:31
  • @OliverCharlesworth: Doesn't the P.O.T. of A->B->C start with A, but the P.O.T. of A<-C->B start with C? – Scott Hunter Sep 28 '14 at 22:33
  • @ScottHunter: Ah, yes. So I meant `B <- A -> C`! – Oliver Charlesworth Sep 28 '14 at 22:34
  • Why not search for the root of the first tree in the second one, then do a direct tree comparison? That would be faster than generating a full preorder just to do a substring search. Also much easier for the next person to maintain the code to understand. – Raymond Chen Sep 28 '14 at 22:38
  • Ok, the null nodes possibly makes a difference (but I don't know off-hand). Either way, the question reduces to "is this representation enough to uniquely reconstruct the original tree?" – Oliver Charlesworth Sep 28 '14 at 22:39

0 Answers0