题解 | #重建二叉树#

重建二叉树

http://www.nowcoder.com/practice/8a19cbe657394eeaac2f6ea9b0f6fcf6

递归递归!

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public TreeNode construct(int[]pre,int[]vin,int pl,int pr,int vl,int vr){
        TreeNode head=new TreeNode(pre[pl]); 
        int i=0;
        for(i=vl;vin[i]!=pre[pl];i++);
        int llen=i-vl;
        int rlen=vr-i;
        if(llen>0){
            head.left=construct(pre,vin,pl+1,pl+llen,vl,vl+llen-1);
        }
        else{
            head.left=null;
        }
        if(rlen>0){
            head.right=construct(pre,vin,pr-rlen+1,pr,vr-rlen+1,vr);
        }
        else{
            head.right=null;
        }
        return head;
    }
    public TreeNode reConstructBinaryTree(int [] pre,int [] vin) {
        if(pre.length==0)
            return null;
        return construct(pre,vin,0,pre.length-1,0,vin.length-1);
        
        
    }
}
全部评论

相关推荐

不愿透露姓名的神秘牛友
07-07 11:20
点赞 评论 收藏
分享
07-11 13:16
湖南工学院 Java
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务