4、重建二叉树

2017-09-02  本文已影响0人  quiterr

题目描述
输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
        TreeNode root = new TreeNode(pre[0]);
        int i = 0;
        while(in[i]!=root.val){
            i++;
        }
        if(i==0){
            root.left = null;
        }else{
            int [] leftPre = new int[i];
            System.arraycopy(pre,1,leftPre,0,i);
            int [] leftIn = new int[i];
            System.arraycopy(in,0,leftIn,0,i);
            root.left = reConstructBinaryTree(leftPre,leftIn);
            
        }
        
        if(i==in.length-1){
            root.right=null;
        }else{
            int [] rightPre = new int[pre.length-i-1];
            System.arraycopy(pre,i+1,rightPre,0,pre.length-i-1);
            int [] rightIn = new int[pre.length-i-1];
            System.arraycopy(in,i+1,rightIn,0,pre.length-i-1);
            root.right = reConstructBinaryTree(rightPre,rightIn);
        }

        return root;
    }
}

第二遍做的时候写的代码:

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
        
        if(pre.length!=in.length||pre.length==0){
            return null;
        }
        
        TreeNode root = new TreeNode(pre[0]);
        
        
        //拆分左右子树
        int rootIndex = -1;
        for(int i=0; i<in.length; i++){
            if(in[i]==pre[0]){
                rootIndex = i;
            }
        }
        // 无法重建二叉树
        if(rootIndex == -1){
            return null;
        }
        
        //存在左子树
        if(rootIndex!=0){
            //左子树的中序
            int[] newLeftIn = new int[rootIndex];
            System.arraycopy(in,0,newLeftIn,0,rootIndex);
            //左子树的前序
            int[] newLeftPre = new int[rootIndex];
            System.arraycopy(pre,1,newLeftPre,0,rootIndex);
            root.left = reConstructBinaryTree(newLeftPre,newLeftIn);
        }
        
        //存在右子树
        if(in.length-rootIndex-1!=0){
            //右子树的中序
            int[] newRightIn = new int[in.length-rootIndex-1];
            System.arraycopy(in,rootIndex+1,newRightIn,0,in.length-rootIndex-1);
            //右子树的前序
            int[] newRigntPre = new int[in.length-rootIndex-1];
            System.arraycopy(pre,1+rootIndex,newRigntPre,0,in.length-rootIndex-1);
            root.right = reConstructBinaryTree(newRigntPre,newRightIn);
        }
        
        
        return root;
    }

}
上一篇下一篇

猜你喜欢

热点阅读