7.2 leetcode 刷题(BST)105(medium)、

105. Construct Binary Tree from Preorder and Inorder Traversal

递归算法注意index的变化!注意Conor case!

class Solution {
    HashMap map=new HashMap<>();
    
    private TreeNode buildTree(int[] preorder,int[] inorder,int sIndex,int eIndex, int preIndex){
        int mIndex= map.get(preorder[preIndex]);
        
        int leftLength=mIndex-sIndex;
        int rightLength=eIndex-mIndex;
        TreeNode node=new TreeNode(inorder[mIndex]);
        if(leftLength>0){
            node.left=buildTree(preorder,inorder,sIndex,mIndex-1,preIndex+1);
        }
        if(rightLength>0){
            node.right=buildTree(preorder,inorder,mIndex+1,eIndex,preIndex+leftLength+1);
        }
        return node;
    }
    
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        if(preorder.length==0l||inorder.length==0||preorder.length!=inorder.length){
            return null;
        }
        
        for(int i=0;i

 

你可能感兴趣的:(tree,leetcode,刷题,BST)