题目描述
输入一颗二叉树的根节点和一个整数,按字典序打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。
实现
- 回溯
时间复杂度 O(N) : N 为二叉树的节点数,先序遍历需要遍历所有节点。
空间复杂度 O(N): 最差情况下,即树退化为链表时,path 存储所有树节点,使用 O(N) 额外空间。
class Solution {
List<List<Integer>> res = new ArrayList<>();
LinkedList<Integer> path = new LinkedList<>();
public List<List<Integer>> pathSum(TreeNode root, int target) {
if (root == null) return res; // 有可能负数相加
int cur = 0;
dfs(root, target, cur);
return res;
}
public void dfs(TreeNode root, int target, int cur) {
cur += root.val;
path.add(root.val);
if (cur == target && (root.left == null && root.right == null)) { //值等 且叶子节点
res.add(new LinkedList<>(path)); //不用考虑树节点,重复节点,但这里是有序队列
}
//非叶子节点继续遍历
if (root.left != null) {
dfs(root.left, target, cur);
}
if (root.right != null) {
dfs(root.right, target, cur);
}
// 必须LinkedList<TreeNode> 而不是List<> 才可以用这个方法
path.removeLast();
}
}