-
Notifications
You must be signed in to change notification settings - Fork 31
/
Copy path257.二叉树的所有路径.cpp
69 lines (59 loc) · 1.52 KB
/
257.二叉树的所有路径.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
/*
* @lc app=leetcode.cn id=257 lang=cpp
*
* [257] 二叉树的所有路径
*/
// @lc code=start
/**
* 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:
std::string makestr(const std::vector<TreeNode *> &nodes)
{
std::string str;
for (int i = 0; i < nodes.size(); ++i)
{
if (i != 0)
{
str.append("->");
}
str.append(std::to_string(nodes[i]->val));
}
return str;
}
void travel(TreeNode *root, std::vector<TreeNode *> &nodes, std::vector<std::string> &result)
{
nodes.push_back(root);
if (root->left == nullptr && root->right == nullptr)
{
result.push_back(makestr(nodes));
}
if (root->left != nullptr)
{
travel(root->left, nodes, result);
}
if (root->right != nullptr)
{
travel(root->right, nodes, result);
}
nodes.pop_back();
}
vector<string> binaryTreePaths(TreeNode *root)
{
std::vector<std::string> result;
std::vector<TreeNode *> nodes;
travel(root, nodes, result);
return result;
}
};
// @lc code=end