题目描述:
给你二叉树的根节点 root 和一个整数目标和 targetSum ,
找出所有从根节点到叶子节点路径总和等于给定目标和的路径。
叶子节点是指没有子节点的节点。
示例1:
输入:root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22
输出:[[5,4,11,2],[5,8,4,5]]
思路与解法(一)——回溯+DFS
套用DFS模板,找到每一个叶子结点,求其路径和,对符合情况的进行记录,不符合情况进行回溯。
class Solution{
// 记录结果
private List<List<Integer>> res = new LinkedList<List<Integer>>();
private LinkedList<Integer> curPath = new LinkedList<>();
public List<List<Integer>> pathSum(TreeNode root, int target) {
dfs(curPath, target, root);
return res;
}
private void dfs(LinkedList<Integer> curPath, int target, TreeNode curRoot) {
if (curRoot == null) {
return;
}
// 添加路径各节点值
curPath.add(curRoot.val);
// 更新target
target -= curRoot.val;
// 判断是否找到
if(target == 0 && curRoot.left == null && curRoot.right == null) {
res.add(new LinkedList<Integer>(curPath));
}
// 典型DFS
dfs(curPath, target, curRoot.left);
dfs(curPath, target, curRoot.right);
// 回溯
curPath.removeLast();
}
}
复杂度分析
时间复杂度:O(N),需要先序遍历所有结点。
空间复杂度:O(N),最差情况下,树退化为链表,需存储所有结点。