leetcode之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 andsum = 22,
return true, as there exist a root-to-leaf path5->4->11->2which sum is 22.
题意
给定一个二叉树,给定一个数字sum,求是否有一条从root->leaf。
c++实现代码
/**
* Definition for binary tree
* 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 == nullptr){
return false;
}
sum -= root->val;
if(root->left == nullptr && root->right == nullptr && sum ==0){
return true;
}
return hasPathSum(root->left,sum) || hasPathSum(root->right,sum);
}
};