原题链接: https://leetcode.com/problems/path-sum-ii/
1. 题目介绍
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.
给出一个二叉树和一个 sum 值,在从根节点到叶子节点的所有路径之中,找出所有节点之和等于 sum 值的路径。
叶子节点是指没有子节点的节点。
Example:
Given the below binary tree and sum = 22,
给出下面的二叉树和sum = 22
返回:
2. 解题思路
深度优先搜索 + 递归解决。
在深度优先搜索遍历树的同时,还需要用 res 记录所经过的节点,用 Count 记录所经过的节点的 val 值之和。
当遇到叶子节点时,如果 Count 和 sum 相等,那么就将这条路径计入满足条件的路径。
如果不是叶子节点,那么就继续遍历左子树和右子树。
注意,分析完每一个节点之后,记得把这个节点从res中删除。
实现代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<List<Integer>> pathSum(TreeNode root, int sum) {
List< List<Integer> > ans = new ArrayList<>();
List<Integer> res = new ArrayList<>();
helper(root , sum, 0, res, ans);
return ans;
}
public void helper(TreeNode node, int sum, int Count, List<Integer> res, List<List<Integer>> ans){
if(node == null){
return;
}
res.add(node.val);
Count += node.val;
if(node.left == null && node.right == null && Count == sum){
List temp = new ArrayList<>(res);
ans.add(temp);
}
helper(node.left , sum , Count , res,ans);
helper(node.right , sum , Count , res,ans);
res.remove(res.size()-1);
}
}