leetcode113.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]
]
从树中找到所有符合条件的从根节点到叶节点路径,条件即为树上所有节点值的和等于目标值。
Path Sum I可以参考这篇博客
思路和代码
其实这里本质上的思路并没有改变,还是采用深度优先算法,采用自顶向下递归的方式将符合条件的结果放入结果集中。
1 | public List<List<Integer>> pathSum(TreeNode root, int sum) { |