题目描述
Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.
给定二叉树和求和,找到所有根到叶路径,其中每个路径的总和等于给定的总和。
Note: A leaf is a node with no children.
注意:叶子是没有子节点的节点。
Example:
Given the below binary tree and sum = 22,
思路与实现
递归(DFS)
class Solution {
private List<List<Integer>> res = new ArrayList<>();
private List<Integer> mid = new ArrayList<>();
public List<List<Integer>> pathSum(TreeNode root, int sum) {
if (root == null)
return res;
dfs(root, 0, sum);
return res;
}
private void dfs(TreeNode node, int sum, int target) {
mid.add(node.val);
if (node.left == null && node.right == null) {
if (sum + node.val == target)
res.add(new ArrayList<>(mid));
} else {
if (node.left != null)
dfs(node.left, sum+node.val, target);
if (node.right != null)
dfs(node.right, sum+node.val, target);
}
mid.remove(mid.size()-1);
}
}
本文介绍了一种解决二叉树路径求和问题的方法,通过递归深度优先搜索(DFS),寻找所有从根节点到叶子节点的路径,使得路径上节点值的总和等于给定的目标值。
378

被折叠的 条评论
为什么被折叠?



