「这是我参与2022首次更文挑战的第27天,活动详情查看:2022首次更文挑战」
路径总和 Path Sum
LeetCode传送门112. 路径总和
题目
给你二叉树的根节点 root 和一个表示目标和的整数 targetSum 。判断该树中是否存在 根节点到叶子节点 的路径,这条路径上所有节点值相加等于目标和 targetSum 。如果存在,返回 true ;否则,返回 false 。
叶子节点 是指没有子节点的节点。
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.
Example:
Input: root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22
Output: true
Explanation: The root-to-leaf path with the target sum is shown.
Input: root = [1,2,3], targetSum = 5
Output: false
Explanation: There two root-to-leaf paths in the tree:
(1 --> 2): The sum is 3.
(1 --> 3): The sum is 4.
There is no root-to-leaf path with sum = 5.
Input: root = [], targetSum = 0
Output: false
Explanation: Since the tree is empty, there are no root-to-leaf paths.
Constraints:
- The number of nodes in the tree is in the range [0, 5000].
- -1000 <= Node.val <= 1000
- -1000 <= targetSum <= 1000
思考线
解题思路
首先看到这道题的题干是比较简单的。只要能找到从root到叶子节点的和为targetSum的路径即可。
而这样找的路线和的个数和叶子结点的个数一样多。我们怎么确定结果呢?
在这里我想到了递归。若判断根节点是否能找到和为targetSum的路径和,我们可以转而去找其左右子节点有没有和为targetSum - root.val的路径和。
我们按照上面的思路不断地递归调用,直到递归到叶子结点。这样我们只要判断leaf.val === targetSum即可。
同时需要注意的是二叉树可能为空,所以我们需要加个非空判定if(!root) return false
根据以上思路,我完成的代码如下:
/**
* 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 hasPathSum(root: TreeNode | null, targetSum: number): boolean {
if (!root) return false;
const val = root.val;
if(!root.left && !root.right) return val === targetSum;
const left = hasPathSum(root.left, targetSum - val);
const right = hasPathSum(root.right, targetSum - val);
return left || right;
};
时间复杂度
O(n): n为二叉树的节点数
这就是我对本题的解法,如果有疑问或者更好的解答方式,欢迎留言互动。