-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path257.binary-tree-paths.cpp
More file actions
66 lines (63 loc) · 1.53 KB
/
257.binary-tree-paths.cpp
File metadata and controls
66 lines (63 loc) · 1.53 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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
/*
* @lc app=leetcode id=257 lang=cpp
*
* [257] Binary Tree Paths
*/
// @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) {}
* };
*/
#include <vector>
#include <string>
#include <sstream>
using namespace std;
class Solution
{
public:
vector<string> binaryTreePaths(TreeNode *root)
{
vector<int> stack;
vector<string> res;
if(root == nullptr)
return res;
dfs(root, stack, res);
return res;
}
void dfs(TreeNode *node, vector<int> &stack, vector<string> &res)
{
stack.push_back(node->val);
if (node->left == nullptr && node->right == nullptr)
{
// leaf
gen_path(stack, res);
}
else
{
if (node->left != nullptr)
dfs(node->left, stack, res);
if (node->right != nullptr)
dfs(node->right, stack, res);
}
stack.pop_back();
}
void gen_path(vector<int> &stack, vector<string> &res)
{
stringstream ss;
for (int i = 0; i < stack.size(); i++)
{
ss << stack[i];
if (i != stack.size() - 1)
ss << "->";
}
res.push_back(ss.str());
}
};
// @lc code=end