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

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

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

/**
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

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

    }

}
*/
public class Solution {
    LinkedList<Integer> path = new LinkedList<>();
    ArrayList<ArrayList<Integer>> result = new ArrayList<>();
    public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int expectNumber) {
        //递归应该能解决吧
         dfs(root,expectNumber);
        return result;
    }
    void dfs(TreeNode root, int target){
        if(root == null){
            return;
        }
        path.add(root.val);
        target -= root.val;
        
        if(target == 0 && root.left == null && root.right == null){
            result.add(new ArrayList<>(path));
        }
        //如果仅仅是为 0 还是需要回溯 或者找其他左 右数递归
        dfs(root.left, target);
        dfs(root.right, target);
        path.removeLast();
    }
}
全部评论

相关推荐

点赞 评论 收藏
分享
03-26 13:44
南华大学 Java
在看面经的花生米很野蛮:这种情况下你当然要回答,你也是吗!!!!我超喜欢他的XXXXX
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务