其他分享
首页 > 其他分享> > 字符串->树 3.重建二叉树(已知中序后序)106

字符串->树 3.重建二叉树(已知中序后序)106

作者:互联网

class Solution {
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        return build(inorder,0,inorder.length-1,postorder,0,postorder.length-1);
    }
    public TreeNode build(int[] inorder, int lo1,int hi1,int[] postorder,int lo2,int hi2){
        if(lo1>hi1 || lo2>hi2)return null;
        int index=lo1;
        for(int i=lo1;i<=hi1;i++){
            if(inorder[i]==postorder[hi2]){
                index=i;
                break;
            }
        }
        int leftsize=index-lo1;
        TreeNode root=new TreeNode(postorder[hi2]);
        root.left=build(inorder,lo1,index-1,postorder,lo2,lo2+leftsize-1);
        root.right=build(inorder,index+1,hi1,postorder,lo2+leftsize,hi2-1);
        return root;
    }
}

标签:index,hi2,int,106,中序,lo1,二叉树,inorder,postorder
来源: https://blog.csdn.net/weixin_47040809/article/details/115427512