-
Notifications
You must be signed in to change notification settings - Fork 6
/
binary_tree_all_paths.cpp
77 lines (60 loc) · 2.07 KB
/
binary_tree_all_paths.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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
/**
* 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:
//recursive
void helper(TreeNode *root, string s, vector<string> &result) {
if(!root) return;
if(!root->left and !root->right) {
result.push_back(s + to_string(root->val));
return;
}
else {
if(root->left)
helper(root->left, s + to_string(root->val) + "->", result);
if(root->right)
helper(root->right, s + to_string(root->val) + "->", result);
}
}
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> result;
helper(root, "", result);
return result;
}
//iterative
vector<string> binaryTreePaths(TreeNode* root) {
if(!root) return {};
queue<TreeNode *> treeQu;
queue<string> strQu;
TreeNode *current = root;
vector<string> result;
string currentStr = "";
treeQu.push(current);
strQu.push(currentStr);
while(!treeQu.empty()) {
current = treeQu.front(); treeQu.pop();
currentStr = strQu.front(); strQu.pop();
if(!current->left and !current->right) {
result.push_back(currentStr + to_string(current->val));
}
if(current->left) {
treeQu.push(current->left);
strQu.push(currentStr + to_string(current->val) + "->");
}
if(current->right) {
treeQu.push(current->right);
strQu.push(currentStr + to_string(current->val) + "->");
}
}
return result;
}
};