「前端刷题」113. 路径总和 II

135 阅读1分钟

「这是我参与2022首次更文挑战的第21天,活动详情查看:2022首次更文挑战」。

题目

链接:leetcode-cn.com/problems/pa…

给你二叉树的根节点 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

思路

  • 题目的意思是找到所有满足从「根节点」到某个「叶子节点」经过的路径上的节点之和等于目标和的路径
  • 用深度优先搜索的方式,枚举每一条从根节点到叶子节点的路径。当我们遍历到叶子节点,且此时路径和恰为目标和时,我们就找到了一条满足条件的路径
  • 为了维护经过的路径,在进入递归的时候要在 path 列表添加节点,结束递归的时候删除节点,跟回溯算法差不多类似的套路

DFS代码实现1

/**
 * @param {TreeNode} root
 * @param {number} targetSum
 * @return {number[][]}
 */
var pathSum = function (root, targetSum) {
  let res = [];
  let path = [];
  const dfs = (root, targetSum) => {
    // 如果节点为空则不需要再递归了
    if (root == null) {
      return;
    }
    // 把当前节点的值加入路径中
    path.push(root.val);
    // 由于路径中加入了当前节点,那目标值就少了
    targetSum -= root.val;
    if (root.left == null && root.right == null && targetSum == 0) {
      // 如果到达叶子节点 并且目标值满足
      res.push(path.concat());
    }
    dfs(root.left, targetSum);
    dfs(root.right, targetSum);
    // 左右子节点都递归完了,把当前节点从路径中删除,可走下一条路径
    path.pop();
  };
  dfs(root, targetSum);
  return res;
};

DFS代码实现2

/**
 * @param {TreeNode} root
 * @param {number} targetSum
 * @return {number[][]}
 */
var pathSum = function (root, targetSum) {
  let curSum = 0;
  let res = [];
  const dfs = (root, path) => {
    if (root == null) return;
    path.push(root.val);
    curSum += root.val;
    if (root.left == null && root.right == null) {
      if (curSum == targetSum) {
        res.push(path.slice());
      }
    }
    dfs(root.left, path);
    dfs(root.right, path);
    path.pop();
    curSum -= root.val;
  };
  dfs(root, []);
  return res;
};

DFS代码实现3

/**
 * @param {TreeNode} root
 * @param {number} targetSum
 * @return {number[][]}
 */
var pathSum = function (root, targetSum) {
  let curSum = 0;
  let res = [];
  let path = [];
  const dfs = (root) => {
    if (root == null) return;
    path.push(root.val);
    curSum += root.val;
    if (root.left == null && root.right == null) {
      if (curSum == targetSum) {
        res.push(path.slice());
      }
    }
    dfs(root.left);
    dfs(root.right);
    path.pop();
    curSum -= root.val;
  };
  dfs(root, []);
  return res;
};