LeetCode 112 Path Sum
程序员文章站
2024-01-05 11:23:40
...
LeetCode 112
Path Sum
-
Problem Description:
给出一棵二叉树,计算二叉树中从根节点到各个叶节点的节点和,如果其中存在等于题目给出的定值sum,则返回true,否则返回false.
具体的题目信息:
https://leetcode.com/problems/path-sum/description/ - Example:
- Solution:
/**
* 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) {
if (root == NULL) return false;
if (root->left == NULL && root->right == NULL && sum-root->val == 0) return true;
return hasPathSum(root->left, sum-root->val)||hasPathSum(root->right, sum-root->val);
}
};
推荐阅读
-
leetcode【112】Path Sum
-
Leetcode算法刷题:第112题 Path Sum
-
leetcode(112):Path Sum
-
leetcode[112]Path Sum
-
LeetCode 112 Path Sum
-
Leetcode Two Sum (java)Longest Substring Without Repeating Characters
-
[LeetCode 4.18] Minimum Path Sum
-
POJ3126 Prime Path(BFS) 类似于Leetcode 单词接龙
-
LeetCode 15: 3Sum题解(python)
-
【LeetCode】Two Sum & Two Sum II - Input array is sorted & Two Sum IV - Input is a BST