根据中序和后序序列来建立二叉树。这里要利用这两种序列的两个特点:
1. 后序序列永远在最后访问根节点
2. 中序序列中根节点分隔左右子树的节点,而这两个左右子节点集合在后序序列中是不交叉的连续出现
根据这两个特点我们可以得到当前节点序列的根节点位置以及左右子节点集合。递归查找左右子节点来建立左子树和右子树完成二叉树的建立。
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode buildTree(int[] inorder, int[] postorder) {
int l = inorder.length;
if( l == 0 )
{
return null;
}
return fun(inorder,0,postorder,0,l);
}
TreeNode fun(int[] inorder,int inst, int[] postorder,int postst, int l)
{
int tmp = postorder[postst+l-1];
int inpos=inst;
for( int i=inst;i<inst+l;i++ )
{
if( inorder[i] == tmp ){
inpos = i;
break;
}
}
TreeNode res = new TreeNode(tmp);
if( inpos == inst )
{
res.left = null;
}
else
{
res.left = fun(inorder,inst,postorder,postst,inpos-inst );
}
if( inpos == inst+l-1 )
{
res.right = null;
}
else
{
res.right = fun(inorder,inpos+1,postorder,postst+inpos-inst,l+inst-1-inpos);
}
return res;
}
}