Given an in-order traversal only for a binary tree (not necessarily a BST), …

Given an in-order traversal only for a binary tree (not necessarily a BST), give a pseudo code to generate all possible binary trees for this traversal sequence.

 

A: 数学归纳法

Firstly of all, with ‘n’ number of nodes, there are (2n)!/n!*(n+1)!

If like the normal definition, in-order is left child->self->right child.
Then in the sequence with length n, we call Partition(sequence) which iteratively pick each one to be the root. All the values on left make the left sub tree and others on right make the right sub tree. So you can call the Partition(subsequence) recursively.

But if you want to know the number of possible trees, I think inductive method could help. If there are N(k) trees correspond to a sequence with length k, then what is N(k+1) by adding the new value or node to the tail of the sequence? I think the answer is 2*N(k). Because you can treat the new node as the last right child or the parent with the previous tree(all possible trees corresponding to sequence k) as its left-child. By knowing N(1) is 1, you have 2^(n-1) for sequence n.

posted @ 2011-12-28 10:23  百分百好牛  阅读(252)  评论(0编辑  收藏  举报