113. Path Sum II

来源:互联网 发布:余世存 知乎 编辑:程序博客网 时间:2024/05/22 18:55

Path Sum II

这里写图片描述

代码

public class Solution {    List<List<Integer>> res = new ArrayList<List<Integer>>();    public List<List<Integer>> pathSum(TreeNode root, int sum) {        if(root == null){            return res;        }        Stack<Integer> path = new Stack<Integer>();        helper(root, sum, path);        return res;    }    public void helper(TreeNode root, int sum, Stack<Integer> path){        path.push(root.val);        if(root.left == null && root.right == null){            if(root.val == sum) res.add(new ArrayList<Integer>(path));        }        if(root.left != null){            helper(root.left, sum-root.val, path);        }        if(root.right != null){            helper(root.right, sum-root.val, path);        }        path.pop();    }}
0 0
原创粉丝点击