in a past exam, we are asked to figure out a unique tree given preorder and inorder traversal. I have briefly touched upon tree permutations before, but I think this is a slightly different question that asks you to understand recursion in tree traversal.
Based on this particular question, I was thinking that given preorder and inorder traversal you can always recreate the unique tree. I don't have a formal proof but the following can probably dressed up into such.
just a reminder:
pre-order = self, pre-order(left subtree), pre-order(right subtree)
in-order = in-order(left subtree), self, in-order(right subtree)
or simply:
pre: self, left, right
in : left, self, right
I can see that the term right should be the last items... so what ever is the matching is the right most "deepest tree".
Next, I go 1 left from in-order that's the "self" which is the parent of the right most item. I find that in the pre-order. I find where this value is from the pre-order. This is the new "self" (parent of the right most item) on the pre so everything between this and right is to the left of this. Now, all the suff here are the left subtree of the tree from the perspective of the parent of the right most node (which may be none btw if there are no matching elements). I repeat this process.
Here, I "traverse" the nodes from right, parent, parent's left subtree. Kind of interesting.
Obviously you can do the same with post and in order. Logic should be the same.
I should add that probably the nodes must be identifiable to reconstruct the tree. ie. repeating values may make it impossible. The obvious example is if all the nodes have the same value. All visits will give the same result.
As for why pre and post order doesn't cut it is kind of intuitive
pre- : self, left, right
post- : left, right, self
There are only two "distinct" blocks. self and (left,right); (but also think in terms of trees). You cannot resolve everything. You see self being on the outter most of both pre and post so you can get rid of those but once you only have left and right... they are identical. Easy counter example would be a two node situation with parent P and child C. P with left child C has the same traversal as P with right child C.
No comments:
Post a Comment