-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary-tree-paths.cpp
More file actions
45 lines (37 loc) · 1.04 KB
/
binary-tree-paths.cpp
File metadata and controls
45 lines (37 loc) · 1.04 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
//
// Created by Chenguang Wang on 2024/2/9.
//
#include "TreeNode.h"
#include <string>
#include <vector>
using namespace std;
class Solution {
public:
vector<string> binaryTreePaths(TreeNode *root) {
vector<string> result;
vector<int> path;
internal(root, path, result);
return result;
}
void internal(TreeNode *root, vector<int> &path, vector<string> &result) {
path.push_back(root->val);
if (root->left == nullptr && root->right == nullptr) {
string p;
int size = path.size();
for (int i = 0; i < size - 1; i++) {
p += to_string(path[i]);
p += "->";
}
p += to_string(path[size - 1]);
result.emplace_back(std::move(p));
}
if (root->left != nullptr) {
internal(root->left, path, result);
path.pop_back();
}
if (root->right != nullptr) {
internal(root->right, path, result);
path.pop_back();
}
}
};