-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinaryTreePaths.cpp
More file actions
57 lines (53 loc) · 1.42 KB
/
BinaryTreePaths.cpp
File metadata and controls
57 lines (53 loc) · 1.42 KB
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
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
string toString(int a){
if(a == 0)
return "0";
string str;
int b=a;
if(a<0){
a = -a;
}
while(a!=0){
str.insert(0, 1, '0'+a%10);
a /= 10;
}
if(b<0)
str.insert(0, 1, '-');
return str;
}
void search(TreeNode* root, string path, vector<string> &res){
if(root == NULL)
return;
path.append("->");
path.append(toString(root->val));
if(root->left != NULL)
search(root->left, path, res);
if(root->right != NULL)
search(root->right, path, res);
if(root->left == NULL && root->right == NULL)
res.push_back(path);
}
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> res;
if(root ==NULL)
return res;
string path = toString(root->val);
if(root->left != NULL)
search(root->left, path, res);
if(root->right != NULL)
search(root->right, path, res);
if(root->left == NULL && root->right == NULL)
res.push_back(path);
return res;
}
};