-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinaryTreePaths.cpp
More file actions
42 lines (39 loc) · 1.14 KB
/
binaryTreePaths.cpp
File metadata and controls
42 lines (39 loc) · 1.14 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
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<string> binaryTreePaths(TreeNode* root) {
ans.clear();
vs.clear();
dfs(root);
return ans;
}
void dfs(TreeNode *root) {
vs.push_back(root->val);
if (!(root -> left) && !(root -> right)) ans.push_back(join());
else {
if (root -> left) dfs(root -> left);
if (root -> right) dfs(root -> right);
}
vs.pop_back();
}
string join() {
return std::accumulate(vs.begin() + 1, vs.end(), to_string(vs[0]),
[](string &ss, int val)
{
return ss + "->" + to_string(val);
});
}
private:
vector<int> vs;
vector<string> ans;
};