LeetCode:105 从前序与中序遍历序列构造二叉树

本来想自己写个二分查找,想了想好累。。。还是遍历吧

class Solution {
    
    public TreeNode binaryTree(int[]preorder,int[]inorder,int start,int end,int begin,int fin)
    {
        
        if(start>end){
            return null;
        }
        TreeNode n = new TreeNode(preorder[start]);
        n.left=null;
        n.right=null;
        int mid=0;
        for(int i=begin;i<=fin;i++){
            if(preorder[start]==inorder[i]){
                mid=i;
                break;
            }
        }
        n.left = binaryTree(preorder,inorder,start+1,start+mid-begin,begin,mid-1);
        n.right= binaryTree(preorder,inorder,start+mid-begin+1,end,mid+1,fin);
        return n;
    }

    public TreeNode buildTree(int[] preorder, int[] inorder) {
        TreeNode t = null;
        if(preorder.length==0||inorder.length==0){
            return null;
        }
        if(preorder==null||inorder==null){
            return null;
        }
        t=binaryTree(preorder,inorder,0,preorder.length-1,0,inorder.length-1);
        
        return t;
    }
}

 

posted @ 2020-10-03 09:32  dlooooo  阅读(165)  评论(0编辑  收藏  举报