-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path257-Binary-Tree-Paths.cpp
More file actions
46 lines (40 loc) · 1.18 KB
/
257-Binary-Tree-Paths.cpp
File metadata and controls
46 lines (40 loc) · 1.18 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
43
44
45
46
class Solution {
public:
vector<vector<int>> ans;
vector<int> path;
vector<string> convert;
vector<string> binaryTreePaths(TreeNode* root) {
if(root) dfs(root);
for(int i=0; i<ans.size(); i++){
string s;
for(int j=0; j<ans[i].size(); j++){
s.append(to_string(ans[i][j]));
if(j < ans[i].size()-1){
s.append("->");
}
}
convert.push_back(s);
}
return convert;
}
void dfs(TreeNode* node){
path.push_back(node->val);
if(!node->left && !node->right){
ans.push_back(path);
path.pop_back();
return;
}
if(node->left) dfs(node->left);
if(node->right) dfs(node->right);
path.pop_back();
return;
}
};
/* 257. Binary-Tree-Paths.cpp
//////////////////////////////////////////////////
Given the root of a binary tree, return all root-to-leaf paths in any order.
Input: root = [1,2,3,null,5]
Output: ["1->2->5","1->3"]
https://leetcode.com/problems/binary-tree-paths/
//////////////////////////////////////////////////
*/