JavaScript / TypeScript for LeetCode (127)

是差点运气,可我一直在努力!

当前进程:

  • 开始时间:2020.6.27
  • 结束时间:undefined

GitHub仓库:https://github.com/Cundefined/JavaScript-or-TypeScript-for-LeetCode

1、题目要求

( LeetCode-第113题 ) 路径总和 II

2、解题思路

方法:深度优先递归 回溯

创建dfs函数:
    1、递归结束条件
    2、将当前非空节点加入路径
    3、将当前节点值从目标sum中减去
    4、碰到叶子节点 就把path加入结果
    5、递归遍历左子树
    6、递归遍历右子树
    7、回溯

2.1、JavaScript Solution

/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} root
 * @param {number} sum
 * @return {number[][]}
 */
var pathSum = function (root, sum) {
  const res = [];

  dfs(root, sum, []);
  return res;

  function dfs(root, sum, path) {
    // 1、递归结束条件
    if (root === null) {
      return;
    }
    // 2、将当前非空节点加入路径
    path.push(root.val);
    // 3、将当前节点值从目标sum中减去
    sum = sum - root.val;
    // 4、碰到叶子节点 就把path加入结果
    if (root.left === null && root.right === null && sum === 0) {
      res.push([...path]);
    }

    // 5、递归遍历左子树
    dfs(root.left, sum, path);

    // 6、递归遍历右子树
    dfs(root.right, sum, path);

    // 7、回溯
    path.pop();
  }
};

2.2、TypeScript Solution

/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

function pathSum(root: TreeNode | null, sum: number): number[][] {
  const res: number[][] = [];

  dfs(root, sum, []);
  return res;

  function dfs(root: TreeNode | null, sum: number, path: number[]): void {
    // 1、递归结束条件
    if (root === null) {
      return;
    }
    // 2、将当前非空节点加入路径
    path.push(root.val);
    // 3、将当前节点值从目标sum中减去
    sum = sum - root.val;
    // 4、碰到叶子节点 就把path加入结果
    if (root.left === null && root.right === null && sum === 0) {
      res.push([...path]);
    }

    // 5、递归遍历左子树
    dfs(root.left, sum, path);

    // 6、递归遍历右子树
    dfs(root.right, sum, path);

    // 7、回溯
    path.pop();
  }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值