112. 路径总和
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 { 12 public: 13 bool hasPathSum(TreeNode* root, int sum) 14 { 15 //如果root为空,直接返回false 16 if(root == NULL) return false; 17 //如果左、右孩子都为空且sum为当前节点的值,返回true 18 if(root->left == NULL && root->right == NULL && sum == root->val) return true; 19 return hasPathSum(root->left,sum - root->val) 20 || hasPathSum(root->right,sum - root->val); 21 } 22 };
    Mamba never out
 
                    
                     
                    
                 
                    
                
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号