面试题34-I 二叉树中和为某一值的路径是否存在

题目:

 

 

解答:

 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     {
14         return helper(root, 0, sum);        
15     }
16 
17     bool helper(TreeNode * root, int cur, int sum)
18     {
19         if (NULL == root)
20         {
21             return false;
22         }
23 
24         cur = cur + root->val;
25         
26         if (root->left == NULL && root->right == NULL)
27         {
28             return cur == sum;
29         }
30         else
31         {
32             return helper(root->left, cur, sum) || helper(root->right, cur, sum);
33         }
34     }
35 };

 

posted @ 2020-05-09 16:01  梦醒潇湘  阅读(223)  评论(0)    收藏  举报