您的位置:首页 > 其它

[leetcode]Path Sum II

2013-06-18 20:46 351 查看
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

      
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: