[JavaScript 刷题] 树 - Path Sum I & II, leetcode 112 & 113

[JavaScript 刷题] 树 - Path Sum I & II, leetcode 112 & 113

github repo 地址: https://github.com/GoldenaArcher/js_leetcode,Github 的目录 大概 会更新的更勤快一些。

112

题目地址:112. Path Sum

112 题目

如下:

Given the root of a binary tree and an integer targetSum, return true if the tree has a root-to-leaf path such that adding up all the values along the path equals targetSum.

A leaf is a node with no children.

112 解题思路

这题解决思路还挺直接的,只需要在到达 leaf 结点时检查一下当前的 targetSum 是否为当前结点的值即可。

不使用 if (!node) return targetSum === 0 是因为有一个边界条件:root = [], targetSum = 0,一个空的节点不管 targetSum 是什么,都应该是 false。但是如果用上面这个边界条件就会导致当传进去的节点为空时,这成了一个可以通过的 case。

算是一个比较简单和普通的 DFS 搜索题了。

112 使用 JavaScript 解题

var hasPathSum = function (root, targetSum) {
    
    
  if (!root) return false;

  if (!root.left && !root.right) return root.val === targetSum;

  const left = hasPathSum(root.left, targetSum - root.val);
  const right = hasPathSum(root.right, targetSum - root.val);

  return left || right;
};

113

题目地址:113. Path Sum II

113 题目

如下:

Given the root of a binary tree and an integer targetSum, return all root-to-leaf paths where the sum of the node values in the path equals targetSum. Each path should be returned as a list of the node values, not node references.

A root-to-leaf path is a path starting from the root and ending at any leaf node. A leaf is a node with no children.

113 解题思路

这题是 112 的升级版,解题思路也和 112 差不多,不过这里需要找到的是所有的路径,而非单独路径。也是一个比较简单的 DFS 的搜索题目,这道题需要注意的一点就是,如果依旧使用 if (!root targetSum === root.val) 做判断条件的话,那么会将同样的路径添加两遍。

113 使用 JavaScript 解题

JavaScript 中函数默认返回 undefined,所以 if (!root targetSum === root.val) 也是可以通过的,不过其他语言可能因为没有返回值而报错。

var pathSum = function (root, targetSum) {
    
    
  if (!root) return [];

  const res = [];

  const isPath = (root, targetSum, path) => {
    
    
    if (!root?.right && !root?.left) {
    
    
      if (targetSum === root.val) res.push([...path, root.val]);

      return;
    }

    if (root.left) isPath(root.left, targetSum - root.val, [...path, root.val]);
    if (root.right)
      isPath(root.right, targetSum - root.val, [...path, root.val]);
  };

  isPath(root, targetSum, []);

  return res;
};

猜你喜欢

转载自blog.csdn.net/weixin_42938619/article/details/125713057