forked from ely-mitu/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pathSum.cpp
104 lines (91 loc) · 2.72 KB
/
pathSum.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
// Source : https://oj.leetcode.com/problems/path-sum/
// Author : Hao Chen
// Date : 2014-06-22
/**********************************************************************************
*
* Given a binary tree and a sum, determine if the tree has a root-to-leaf path
* such that adding up all the values along the path equals the given sum.
*
* For example:
* Given the below binary tree and sum = 22,
*
* 5
* / \
* 4 8
* / / \
* 11 13 4
* / \ \
* 7 2 1
*
* return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.
*
**********************************************************************************/
#include <time.h>
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
Solution(){
srand(time(NULL));
}
bool hasPathSum(TreeNode *root, int sum) {
return hasPathSum3(root, sum, 0);
return hasPathSum2(root, sum);
return hasPathSum1(root, sum);
}
bool hasPathSum3(TreeNode* root, int sum, int s) {
if ( root == NULL) return false;
s += root->val;
if ( !root->left && !root->right) return s == sum;
return (hasPathSum3(root->left, sum, s) || hasPathSum3(root->right, sum, s));
}
bool hasPathSum1(TreeNode *root, int sum) {
if (root==NULL) return false;
vector<TreeNode*> v;
v.push_back(root);
while(v.size()>0){
TreeNode* node = v.back();
v.pop_back();
if (node->left==NULL && node->right==NULL){
if (node->val == sum){
return true;
}
}
if (node->left){
node->left->val += node->val;
v.push_back(node->left);
}
if (node->right){
node->right->val += node->val;
v.push_back(node->right);
}
}
return false;
}
bool hasPathSum2(TreeNode *root, int sum) {
if (root==NULL) return false;
if (root->left==NULL && root->right==NULL ){
return (root->val==sum);
}
if (root->left){
root->left->val += root->val;
if (hasPathSum2(root->left, sum)){
return true;
}
}
if (root->right){
root->right->val += root->val;
if (hasPathSum2(root->right, sum)){
return true;
}
}
return false;
}
};