跳至主要內容

112. 路径总和


112. 路径总和

🟢   🔖  深度优先搜索 广度优先搜索 二叉树  🔗 力扣open 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[✓] 深度优先搜索 回溯 1+🟠🀄️open in new window 🔗open in new window
124二叉树中的最大路径和[✓] 深度优先搜索 动态规划 1+🔴🀄️open in new window 🔗open in new window
129求根节点到叶节点数字之和[✓] 深度优先搜索 二叉树🟠🀄️open in new window 🔗open in new window
437路径总和 III[✓] 深度优先搜索 二叉树🟠🀄️open in new window 🔗open in new window
666路径总和 IV 🔒 深度优先搜索 数组 2+🟠🀄️open in new window 🔗open in new window