lintcode:前序遍历和中序遍历树构造二叉树

根据前序遍历和中序遍历树构造二叉树.

样例

给出中序遍历:[1,2,3]和前序遍历:[2,1,3]. 返回如下的树:

  2
 / \
1   3

思路:

前序: 2 1 4 5 3 6

中序: 4 1 5 2 6 3

首先根据前序的第一个元素可知 根节点为2, 然后在中序中寻找2, 然后在2之前的元素就

可知是 左子树的元素,那么左子树的元素个数就知道了。 然后左右子树的 前序, 中序 都可知了,

最后递归即可。

Java代码:

    public static TreeNode buildTree_run(int[] inorder, int[] postorder) {
        // write your code here
        if(inorder.length!=postorder.length){
            return null;
        }
        return build(inorder, 0, inorder.length-1,  postorder, 0, postorder.length);
    }


    public TreeNode build(int[] inorder, int inpre, int inlast, int[] postorder, int postpre, int postlast){
        if(inpre>inlast){return null; }
        // 先找到根节点
        TreeNode node = new TreeNode(postorder[postpre]);
        // 在中序中找到根的位置
        int i = inpre;
        for(;i<=inlast;i++){
            if(inorder[i] == postorder[postpre]){break;}
        }
        node.left = build(inorder, inpre, i-1, postorder, postpre+1, postpre+i-inpre);
        node.right = build(inorder, i+1, inlast, postorder, postpre+i-inpre+1, postlast);
        return node;
    }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值