递归:
// 递归
public List<List<Integer>> pathSum(TreeNode root, int sum) {
List<List<Integer>> res = new ArrayList<>();
List<Integer> out = new ArrayList<>();
dfsPathSum(root, sum, out, res);
return res;
}
public void dfsPathSum(TreeNode node, int sum, List<Integer> out, List<List<Integer>> res) {
if (node == null)
return;
out.add(node.val);
if (sum == node.val && node.left == null && node.right == null) {
List<Integer> newList = new ArrayList<Integer>(out);
res.add(newList);
}
dfsPathSum(node.left, sum - node.val, out, res);
dfsPathSum(node.right, sum - node.val, out, res);
out.remove(out.size() - 1);
}
迭代:
public List<List<Integer>> pathSum1(TreeNode root, int sum) {
List<List<Integer>> res = new ArrayList<>();
List<TreeNode> s = new ArrayList<>();
TreeNode cur = root, pre = null;
int val = 0;
while (cur != null || !s.isEmpty()) {
while (cur != null) {
s.add(cur);
val += cur.val;
cur = cur.left;
}
cur = s.get(s.size() - 1);
if (cur.left == null && cur.right == null && val == sum) {
List<Integer> v = new ArrayList<>();
for (TreeNode it : s) {
v.add(it.val);
}
res.add(v);
}
if (cur.right != null && cur.right != pre)
cur = cur.right;
else {
pre = cur;
val -= cur.val;
s.remove(s.size() - 1);
cur = null;
}
}
return res;
}