欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

LeetCode 106 Construct Binary Tree from Inorder and Postorder Traversal

程序员文章站 2022-04-27 11:35:32
...

1.

LeetCode 106 Construct Binary Tree from Inorder and Postorder Traversal

2.

class Solution {
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        if(postorder==null||postorder.length==0||inorder==null||inorder.length==0||
           postorder.length!=inorder.length){
            return null;
        }   
        return buildTreeCore(postorder,0,postorder.length-1,inorder,0,inorder.length-1);   
    }
    public TreeNode buildTreeCore(int[] postorder, int postLeft, int postRight, int[] inorder, int inLeft, int inRight) {
        if(postLeft>postRight||inLeft>inRight){
            return null;
        }
        TreeNode root=new TreeNode(postorder[postRight]);     
        for(int i=inLeft;i<=inRight;i++){
            if(root.val==inorder[i]){
                root.left=buildTreeCore(postorder,postLeft,postLeft+i-inLeft-1,inorder,inLeft,i-1);
                root.right=buildTreeCore(postorder,postLeft+i-inLeft,postRight-1,inorder,i+1,inRight);
            }
        }
        return root;        
    }
}