跳至主要內容

112. Path Sum


112. Path Sumopen in new window

🟢   🔖  深度优先搜索 广度优先搜索 二叉树  🔗 LeetCodeopen in new window

题目

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 1:

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.

Example 2:

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.

Example 3:

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

题目大意

给定一个二叉树和一个目标和,判断该树中是否存在根节点到叶子节点的路径,这条路径上所有节点值相加等于目标和。说明: 叶子节点是指没有子节点的节点。

解题思路

递归求解即可

代码

/**
 * @param {TreeNode} root
 * @param {number} targetSum
 * @return {boolean}
 */
var hasPathSum = function (root, targetSum) {
	if (!root) return false;
	if (!root.left && !root.right) return root.val == targetSum;
	return (
		hasPathSum(root.left, targetSum - root.val) ||
		hasPathSum(root.right, targetSum - root.val)
	);
};

相关题目

相关题目
- [113. 路径总和 II](./0113.md)
- [124. 二叉树中的最大路径和](https://leetcode.com/problems/binary-tree-maximum-path-sum)
- [129. 求根节点到叶节点数字之和](./0129.md)
- [437. 路径总和 III](https://leetcode.com/problems/path-sum-iii)
- [🔒 Path Sum IV](https://leetcode.com/problems/path-sum-iv)