-
Notifications
You must be signed in to change notification settings - Fork 0
/
binarytreepaths.cpp
34 lines (33 loc) · 938 Bytes
/
binarytreepaths.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
/**
* 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 pathFinder(TreeNode *ptr, vector<string> &paths, string curr) {
if (ptr) {
curr = curr + "->" + to_string(ptr->val);
pathFinder(ptr->left,paths,curr);
pathFinder(ptr->right,paths,curr);
if (!ptr->left && !ptr->right)
paths.push_back(curr);
}
}
vector<string> binaryTreePaths(TreeNode* root) {
string curr;
vector<string> paths;
if (root) {
curr = to_string(root->val);
pathFinder(root->left,paths,curr);
pathFinder(root->right,paths,curr);
}
if (!paths.size() && root)
paths.push_back(curr);
return paths;
}
};