[leetcode]Path Sum II

时间:2021-05-04 11:28:50
Path Sum II

Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.

For example:
Given the below binary tree and sum = 22,

              5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1

return

[
[5,4,11,2],
[5,8,4,5]
] 这个问题需要返回每条满足sum值的所有路径。思路是:后序遍历,回溯时将当前node.val添加到左右子树的结果中。 递归:
List<List<Int>> path_sum_helper(Treenode node, int current_sum, int depth, int sum_aim):
  if (node is leaf-node):
    r = [[]]
    if (current_sum == sum_aim):
      r_i = []
      r_i[depth] = node.val
      r.add(r_i)
    return r
  else:
    r = [[]]
    if(node.left != null):
      left_ = path_sum_helper(node.left, current_sum + node.left.val, depth + 1, sum_aim)
      if (left_ != null):
        r = left_;
        for(r_ : r):
          r_[level] = node.val
      // similar for right sub-tree
      // need to merge left and right results
    return r