重建二叉树

重建二叉树,由前序遍历和中序遍历创建二叉树。这个可以递归实现。先找到根节点,然后找到前序遍历的数组和中序遍历的数组,即可实现。

public TreeNode constructBinary(int[] pre, int[] in){
        if(pre.length == 0 || in.length ==0 ||pre.length!=in.length){
            return null;
        }
        TreeNode root = new TreeNode(pre[0]);
        int i=0;
        int n = in.length;
        for(;i<n;i++){
            if(in[i] == pre[0]){
                break;
            }
        }
        int[] leftPre = new int[i-1];
        int[] rightPre = new int[n-i];
        int[] leftIn = new int[i-1];
        int[] rightIn = new int[n-i];
        System.arraycopy(pre,1,leftPre, 0,i-1);
        System.arraycopy(pre, i+1, rightPre,0,n-i);
        System.arraycopy(in,0,leftIn, 0,i-1);
        System.arraycopy(in, i+1,rightIn,0,n-i);
        root.left = constructBinary(leftPre,leftIn);
        root.right = constructBinary(rightPre,rightIn);
        return root;
    }

 

posted @ 2016-08-27 16:56  樱圃  阅读(108)  评论(0编辑  收藏  举报