[leetcode]112. Path Sum
Analysis
新的一天新的刷题,中午吃什么比较好呢—— [好想好想吃冰淇淋啊~]
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.
深度优先搜索一棵二叉树,看是否存在一条路径,使得路径上的节点和等于给定数值,递归解决就行了~
Implement
/**
* 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 find(root, sum);
}
bool find(TreeNode* root, int sum){
if(root==NULL)
return false;
if(root->left==NULL && root->right==NULL){
if(root->val == sum)
return true;
else
return false;
}
return find(root->left, sum-root->val) || find(root->right, sum-root->val);
}
};