5、路径总和

递归思想

sum的值往下累减

左子树或右子树的值符合即可

注意root为空的情况

当来到叶子节点时(左右子树为空),判断它的值是否等于sum

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     bool hasPathSum(TreeNode* root, int sum) {
13         if(root == NULL) return false;
14         if((root->left==NULL&&root->right==NULL)&&root->val==sum)return true;
15         return hasPathSum(root->left,sum-root->val)|| hasPathSum(root->right,sum-root->val);
16         
17     }
18 };

 

posted @ 2020-07-07 15:44  Gumpest  阅读(52)  评论(0)    收藏  举报