leetcode 路径总和
并无太好的思路,便网上学习了大神的解法,在此记录
思路:利用递归,将sum值减去当前根节点值,对左右子树进行递归,当递归到叶子节点时,判断sum值是否减为了0;
/**
* 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==nullptr)
{
return false;
}
int tmp=sum-root->val;
if(root->left==nullptr&&root->right==nullptr)
{
return tmp==0 ? true:false;
}
return hasPathSum(root->left,tmp)||hasPathSum(root->right,tmp);
}
};
总结:不应该太相信自己的思维,当没有思路时去学习一下大神的方法,也是很大的进步,毕竟不能生而知之,没有见过好的方法,怎么能创造出好的方法。