题解 | #二叉树中和为某一值的路径(二)#

二叉树中和为某一值的路径(二)

http://www.nowcoder.com/practice/b736e784e3e34731af99065031301bca

import java.util.ArrayList;
/**
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}
*/
public class Solution {
    public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int expectNumber) {
        ArrayList<ArrayList<Integer>> list = new ArrayList<ArrayList<Integer>>();
        if(root==null){
            return list;
        }
        
        helper(root, expectNumber, new ArrayList<Integer>(), 0, list);
        return list;
    }
    
    public static void helper(TreeNode root, int expectNumber, 
                              ArrayList<Integer> curList, int curSum, ArrayList<ArrayList<Integer>> list){
        if(root==null){
            return;
        }
        
        if(root.left ==null&& root.right==null){
            if(curSum+ root.val ==expectNumber){
                ArrayList<Integer> curListCopy = new ArrayList<Integer>(curList);
                curListCopy.add(root.val);
                list.add(curListCopy);
            }
            return;
        }
        
        curList.add(root.val);
        curSum+=root.val;
        
        helper(root.left, expectNumber, curList, curSum, list);
        helper(root.right, expectNumber, curList, curSum, list);
        
        curList.remove(curList.size()-1);
    }
}

全部评论

相关推荐

被加薪的哈里很优秀:应该继续招人,不会给你留岗位的
点赞 评论 收藏
分享
能干的三文鱼刷了100道题:公司可能有弄嵌入式需要会画pcb的需求,而且pcb能快速直观看出一个人某方面的实力。看看是否有面试资格。问你问题也能ai出来,pcb这东西能作假概率不高
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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