leetcode: Construct Binary Tree from Inorder and Postorder Traversal

根据中序和后序序列来建立二叉树。这里要利用这两种序列的两个特点:

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;
    }
    
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值