题目
输入一棵二叉树和一个整数,打印出二叉树中节点值的和为输入整数的所有路径。从树的根节点开始往下一直到叶节点所经过的节点形成一条路径。
示例:
给定如下二叉树,以及目标和 sum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1
返回:
[
[5,4,11,2],
[5,8,4,5]
]
提示:
节点总数 <= 10000
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/er-cha-shu-zhong-he-wei-mou-yi-zhi-de-lu-jing-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路
从根节点开始遍历先加到list里、sum减去当前根节点的值,
如果左子节点不为空把左子节点当成根节点做上面的操作,
如果右子节点不为空把右子节点当成根节点做上面的操作。
当sum等于0时,左右子节点都为空时,那么这就是一条路径,
把list加到返回list里。如果不是就从list移除最后一个值。
代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public static List<List<Integer>> result;
public static List<Integer> resultOne;
public List<List<Integer>> pathSum(TreeNode root, int sum) {
result = new ArrayList<>();
resultOne = new ArrayList<>();
if (root == null) return result;
help(root, sum);
return result;
}
public void help(TreeNode root, int sum) {
resultOne.add(root.val);
sum -= root.val;
if (sum == 0 && root.left == null && root.right == null) {
this.result.add(new ArrayList<>(resultOne));
} else {
if (root.left != null) {
help(root.left, sum);
}
if (root.right != null) {
help(root.right, sum);
}
}
resultOne.remove(resultOne.size() - 1);
}
}