根据一棵树的中序遍历与后序遍历构造二叉树

根据一棵树的中序遍历与后序遍历构造二叉树

根据一棵树的中序遍历与后序遍历构造二叉树。

注意:
你可以假设树中没有重复的元素。

例如,给出

中序遍历 inorder = [9,3,15,20,7]
后序遍历 postorder = [9,15,7,20,3]
返回如下的二叉树:

 3
/ \
9  20
  /  \
  15   7
 public int postIndex = 0;
    public TreeNode2 buildTreeChild1(int[] inorder, int[] postorder,int inbegin,int inend) {
        //判断是否有左树或者是右树
        if(inbegin > inend) {
            return null;
        }
        TreeNode2 root = new TreeNode2(postorder[postIndex]);
        //找root在中序遍历的下标
        int rootIndex = findIndexOfInorder1(inorder,inbegin,inend,postorder[postIndex]);
        postIndex--;


        root.right = buildTreeChild1(inorder,postorder ,rootIndex+1,inend);


        root.left = buildTreeChild1(inorder ,postorder,inbegin, rootIndex-1);


        return root;
    }


    public int findIndexOfInorder1(int[] inorder,int inbegin, int inend,int val){
        for(int i = inbegin;i <= inend;i++) {
            if(inorder[i] == val) {
                return i;
            }
        }
        return -1;
    }


    public TreeNode2 buildTree(int[] inorder, int[] postorder) {
        if(postorder == null || inorder == null) {
            return null;
        }
        if(postorder.length == 0 || inorder.length ==0) {
            return null;
        }
        postIndex = postorder.length-1;
        return buildTreeChild1(inorder,postorder,0,inorder.length-1);
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值