-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary_tree_paths_257.cpp
More file actions
41 lines (38 loc) · 934 Bytes
/
Copy pathbinary_tree_paths_257.cpp
File metadata and controls
41 lines (38 loc) · 934 Bytes
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
/**
* 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:
void buildPath(TreeNode* root, vector<string>& res, string path)
{
if (!root) return;
path += "->";
path += to_string(root->val);
if (!root->left && !root->right) //leaf node
{
res.push_back(path);
return;
}
buildPath(root->left, res, path);
buildPath(root->right, res, path);
}
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> res;
if (!root) return res;
string rootnode = to_string(root->val);
if (!root->left && !root->right)
{
res.push_back(rootnode);
return res;
}
buildPath(root->left, res, rootnode);
buildPath(root->right, res, rootnode);
return res;
}
};