-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path257.cpp
34 lines (34 loc) · 936 Bytes
/
257.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
// recursion-6ms.cpp
/**
* 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:
vector<string> binaryTreePaths(TreeNode *root) {
vector<string> result;
if (root == NULL)
return result;
if (root->left == NULL && root->right == NULL) {
result.push_back(to_string(root->val));
return result;
}
preOrder(result, root->left, to_string(root->val));
preOrder(result, root->right, to_string(root->val));
return result;
}
void preOrder(vector<string> &result, TreeNode *root, string str) {
if (root == NULL)
return;
str += "->" + to_string(root->val);
if (root->left == NULL && root->right == NULL)
result.push_back(str);
preOrder(result, root->left, str);
preOrder(result, root->right, str);
}
};