path sum I II

path sum I II

I

When NULL == root, no matter sum's value return false.

 1 /**
 2  * Definition for binary tree
 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 ) {
14             return false;
15         }
16         if ( root->val == sum && !root->left && !root->right ) {
17             return true;
18         }
19         return ( hasPathSum(root->left,sum-root->val) || hasPathSum(root->right,sum-root->val) );
20     }
21 };

II not hard too

DFS can take this.

 1 /**
 2  * Definition for binary tree
 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 private:
12     vector< vector< int > > result;
13 public:
14     vector<vector<int> > pathSum(TreeNode *root, int sum) {
15         result.clear();
16         if ( !root ) {
17             return result;
18         }
19         vector< int > t;
20         DFS(root,sum,t);
21         return result;
22     }
23     void DFS( TreeNode* root, int sum, vector< int >& t ) {
24         if ( root->val == sum && !root->left && !root->right ) {
25             t.push_back(root->val);
26             result.push_back(t);
27             t.pop_back();
28         }
29         if ( !root->left && !root->right ) {
30             return;
31         }
32         t.push_back(root->val);
33         if ( root->left ) {
34             DFS(root->left,sum-root->val,t);
35         }
36         if ( root->right ) {
37             DFS(root->right,sum-root->val,t);
38         }
39         t.pop_back();
40     }
41 };

Loading Disqus comments...
Table of Contents