-
Notifications
You must be signed in to change notification settings - Fork 0
/
257-Binary Tree Paths.cpp
50 lines (48 loc) · 1.24 KB
/
257-Binary Tree 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
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
#include <stdio.h>
#include <stdlib.h>
#include <string>
class Solution {
private:
vector<vector<int>> ans;
vector<int> tmp;
void dfs(TreeNode* root){
if(root == NULL) return;
tmp.push_back(root->val);
if(root->left == NULL && root->right == NULL){
ans.push_back(tmp);
}
if(root->left != NULL)
dfs(root->left);
if(root->right != NULL)
dfs(root->right);
tmp.erase(tmp.end()-1);
}
public:
vector<string> binaryTreePaths(TreeNode* root) {
dfs(root);
vector<string> sans;
char buffer[10];
for(int i = 0; i < ans.size(); i++){
string s="";
for(int j = 0; j < ans[i].size()-1; j++){
sprintf(buffer, "%d", ans[i][j]);
//itoa(ans[i][j],buffer,10);
s += buffer;
s += "->";
}
sprintf(buffer, "%d", ans[i][ans[i].size()-1]);
s+= buffer;
sans.push_back(s);
}
return sans;
}
};