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

LeetCode 105 Construct Binary Tree from Preorder and Inorder Traversal

程序员文章站 2022-06-18 18:47:17
...

1.

LeetCode 105 Construct Binary Tree from Preorder and Inorder Traversal

2

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

.