由前序遍历和中序遍历构建二叉树

public Node reConstructBinaryTree(int[] pre,int[] in){
        if(pre==null || in ==null){
            return null;
        }
        Node mm = reConstructBinaryTree(pre,in,0,pre.length-1,0,in.length-1);
        return mm;
    }
    public Node reConstructBinaryTree(int[] pre,int[] in,int preStart,int preEnd,int inStart,int inEnd){
        Node node = new Node(pre[preStart]);
        node.left = null;
        node.right = null;
        if(preStart == preEnd && inStart == inEnd){
            return node;
        }
        int root = 0;
        for(root = instart;root<inEnd;root++){
            if(pre[preStart] == in[root]){
                break;
            }
        }
        int leftLength = root-inStart;
        int rightLength = inEnd-root;
        if(leftLength>0){
            node.left = reConstructBinaryTree(pre,in,preStart+1,preStart+leftLength,inStart,root-1);
        }
        if(rightLength>0){
            node.right = reConstructBinaryTree(pre,in,preStart+leftLength,root+1,inEnd);
        }
        return node;
    }

 

posted @ 2018-07-09 00:33  樱圃  阅读(347)  评论(0编辑  收藏  举报