-
Notifications
You must be signed in to change notification settings - Fork 0
/
257.hpp
54 lines (46 loc) · 1.13 KB
/
257.hpp
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
#ifndef LEETCODE_257_HPP
#define LEETCODE_257_HPP
#include <iostream>
#include <queue>
#include <algorithm>
#include <vector>
#include <unordered_map>
#include <unordered_set>
#include <set>
#include <numeric>
#include <stack>
#include <string>
#include "../common/leetcode.hpp"
using namespace std;
class Solution {
public:
vector<string> binaryTreePaths(TreeNode *root) {
path.clear();
vector<string> paths;
dfs(paths, root);
return paths;
}
private:
deque<int> path;
string path2s() {
string s;
for (int i = 0; i < path.size(); ++i) {
s.append(to_string(path[i]));
s.append("->");
}
return s;
}
void dfs(vector<string> &paths, TreeNode *node) {
if (node == nullptr)
return;
else if (node->right == nullptr && node->left == nullptr)
paths.emplace_back(path2s().append(to_string(node->val)));
else {
path.emplace_back(node->val);
dfs(paths, node->left);
dfs(paths, node->right);
path.pop_back();
}
}
};
#endif //LEETCODE_257_HPP