LeetCode-113不同路径II

问题

给你二叉树的根节点 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]]
示例 2:

输入:root = [1,2,3], targetSum = 5
输出:[]
示例 3:

输入:root = [1,2], targetSum = 0
输出:[]

提示:

  • 树中节点总数在范围 [0, 5000]
  • -1000 <= Node.val <= 1000
  • -1000 <= targetSum <= 1000

思路

深度优先搜索+回溯法

代码

List<List<Integer>> lists=new ArrayList<>();
Deque<Integer> path = new LinkedList<>();
public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
    DFS(root,targetSum);
    return lists;
}

public void DFS(TreeNode root, int sum){
    if(root==null) return;
    //入队
    path.offer(root.val);
    sum-=root.val;
    if (root.left==null&&root.right==null&&sum==0)
        lists.add(new LinkedList<>(path));

    DFS(root.left,sum);
    DFS(root.right,sum);
    //我们要理解递归的本质,当递归往下传递的时候他最后还是会往回走,
    //我们把这个值使用完之后还要把它给移除,这就是回溯
    path.pollLast();
    // Deque path使用removeLast/pollLast,使用下边的代码会出错
    //List path使用下边代码不会出错,相应offer改为add
    //path.remove(path.size()-1);
} 
posted @ 2021-03-11 21:54  _且歌且行  阅读(41)  评论(0)    收藏  举报