leetcode:
https://leetcode-cn.com/problems/er-cha-shu-zhong-he-wei-mou-yi-zhi-de-lu-jing-lcof/
题目描述
输入一棵二叉树和一个整数,打印出二叉树中节点值的和为输入整数的所有路径。从树的根节点开始往下一直到叶节点所经过的节点形成一条路径。
示例
给定如下二叉树,以及目标和 sum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1
返回:
[
[5,4,11,2],
[5,8,4,5]
]
题解(双百解法)
/**
* 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>> result = new LinkedList<>();
LinkedList<Integer> stack = new LinkedList<>();
int sum;
public List<List<Integer>> pathSum(TreeNode root, int sum) {
if(root == null) return result;
this.sum = sum;
dfs(root, root, 0);
return result;
}
public void dfs(TreeNode current, TreeNode parent, int curSum){
if(current == null){
//parent.left == null --> 父结点为叶子结点
//只有当父结点的右子结点为空时才能进入该判断条件
if(curSum == sum && parent.left == null){
result.add((LinkedList)stack.clone());
}
stack.add(0);
return;
}
curSum += current.val;
stack.add(current.val);
// 若左子结点不为空,则当前结点一定不为叶子结点
if(current.left != null){
dfs(current.left, current, curSum);
stack.removeLast();
}
dfs(current.right, current, curSum);
stack.removeLast();
// 回退
curSum -= current.val;
}
}