0
点赞
收藏
分享

微信扫一扫

LeetCode: 112. Path Sum


LeetCode: 112. Path Sum

题目描述

Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.

For example:
Given the below binary tree and sum = 22,

5
/ \
4 8
/ / \
11 13 4
/ \ \
7 2 1

return true, as there exist a root-to-leaf path ​​5->4->11->2​​ which sum is 22.

题目大意: 判断给定二叉树中是否有个根节点到叶节点的路径,使得路径上的数值的和是给定的数。

解题思路 —— 递归求解

要满足从 ​​root​​​ 到叶节点的和为 ​​sum​​​, 只需要满足从左/右孩子到叶节点的和为 ​​sum - root->val​​ 即可。

AC 代码

/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;[](h
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool hasPathSum(TreeNode* root, int sum) {
if(root == nullptr) return false;
if(root->left == nullptr && root->right == nullptr && root->val == sum) return true;
return hasPathSum(root->left, sum - root->val) || hasPathSum(root->right, sum - root->val);
}

实际上,可以合并成一行代码:

/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool hasPathSum(TreeNode* root, int sum) {
return root != nullptr &&
((root->left == nullptr && root->right == nullptr && root->val == sum) ||
hasPathSum(root->left, sum - root->val) || hasPathSum(root->right, sum - root->val));
}
};


举报

相关推荐

0 条评论