题解:基于递归 | #二叉树根节点到叶子节点的所有路径和#

重建二叉树

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



import java.util.*;
/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    int[] pre;
    int[] vin;
    int p;//记录pre中,已经被处理到的节点的索引
    
    public TreeNode reConstructBinaryTree(int [] pre,int [] vin) {
        this.pre = pre;
        this.vin = vin;
        p=0;
        return reConstructBinaryTree(0,pre.length-1);
    }
    public TreeNode reConstructBinaryTree(int start,int end) {
        for(int i=start;i<=end;i++){
            if(vin[i]==pre[p]){
                TreeNode node=new TreeNode(pre[p]);
                p++;
                node.left=reConstructBinaryTree(start,i-1);
                node.right=reConstructBinaryTree(i+1,end);
                return node;
            }
        }
        return null;
    }
}
全部评论

相关推荐

不愿透露姓名的神秘牛友
07-01 17:00
点赞 评论 收藏
分享
程序员小白条:你是沟通了900个,不是投了900份简历,你能投900份,意味着对面都要回复你900次,你早就找到实习了,没亮点就是这样的,别局限地区,时间投的也要早,现在都要7月了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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