定一个二叉树和一个目标和,找到所有从根节点到叶子节点路径总和等于给定目标和的路径。
说明: 叶子节点是指没有子节点的节点。
示例:
给定如下二叉树,以及目标和 sum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1
返回:
[
[5,4,11,2],
[5,8,4,5]
]
112 - 路径总和 - python中只需要判断是否存在路径的总和等于给定的目标和,而该题需要找到所有满足条件的路径。因此,我们需要在回溯寻找路径的同时保存访问过的节点。
- 如果树为空,则直接返回空数组
- 否则从根节点出发找满足条件的路径
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def pathSum(self, root: TreeNode, sum_: int) -> List[List[int]]:
def track(root, path, sum_):
if not root:return
if not root.left and not root.right and sum_ == root.val:
path.append(root.val)
res.append(path[:])
path.pop()
path.append(root.val)
sum_ -= root.val
track(root.left, path, sum_ )
track(root.right, path, sum_)
path.pop()
if not root: return []
res = []
track(root, [], sum_)
return res
Java中我们需要使用List来保存所有可能的路径,并且使用List来保存访问过的节点,整体的解题代码如下所示:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
List<List<Integer>> results = new LinkedList<List<Integer>>();
public List<List<Integer>> pathSum(TreeNode root, int sum) {
if(root == null){
return results;
}
LinkedList<Integer> path = new LinkedList<>();
track(root, path, sum);
return results;
}
public void track(TreeNode root, LinkedList<Integer> path, int sum){
if(root == null){
return;
}
if(root.left == null && root.right == null && sum == root.val){
path.add(root.val);
results.add(new LinkedList(path));
path.removeLast();
}
path.add(root.val);
sum -= root.val;
track(root.left, path, sum);
track(root.right, path, sum);
path.removeLast();
}
}