算法题分享 | 路径总和 II

85 阅读2分钟

image.png

题目

给你二叉树的根节点 root 和一个整数目标和 targetSum ,找出所有 从根节点到叶子节点 路径总和等于给定目标和的路径。

叶子节点 是指没有子节点的节点。

 

示例 1:

image.png

输入: 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:

image.png

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

示例 3:

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

提示:

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

题解

解题思路

可基于深度优先搜索遍历每条路径,对于每条路径,都判断路径节点值的和是否是 targetSum,若是,即加入到结果集合中。

代码

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {

    // 用于保存所有符合要求的路径
    List<List<Integer>> res;

    public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
        // 初始化 res
        res = new ArrayList<List<Integer>>();
        // 开始深度优先搜索
        dfs(new ArrayList<Integer>(), root, targetSum);
        return res;
    }

    /**
     * curPath: 记录当前已遍历的节点
     * root:当前遍历的子树根节点
     * resSum: 当前剩余的节点和,每遍历到一个节点,都会给该值减去节点值,遍历到叶子节点时,若该值减为 0,则表示路径符合要求
     */
    public void dfs(List<Integer> curPath, TreeNode root, int resSum) {

        // 提前返回
        if (root == null) {
            return;
        }

        curPath.add(root.val);

        if (root.left == null && root.right == null && resSum - root.val == 0) {
            // 路径符合要求 加入
            res.add(new ArrayList(curPath));
        } else {
            // 遍历左子树
            dfs(curPath, root.left, resSum - root.val);
            // 遍历右子树
            dfs(curPath, root.right, resSum - root.val);
        }
        // 返回本次递归前,先移除当前节点
        curPath.remove(curPath.size() - 1);
    }
}

复杂度分析

  • 时间复杂度:O(N²)
    其中 N 是树的节点数。在最坏的情况下,路径的数目为 O(N), 并且每条路径的节点个数也为 O(N),所以要遍历完这些路径,时间复杂度是 O(N²)。
  • 空间复杂度:O(N)
    空间复杂度来源于递归时栈空间的开销,栈的元素个数不会大于树的节点个数。