-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathleetcode_257
55 lines (52 loc) · 1.23 KB
/
leetcode_257
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
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
//先根遍历,用stack存
void in_order(TreeNode* root,stack<string>& sk,vector<string> &ans)
{
stringstream stream;
stream<<root->val;
string temp=stream.str();
temp+="->";
if(!sk.empty())
{
string sk_top=sk.top();
sk.pop();
temp=sk_top+temp;
}
if(root->left)
{
sk.push(temp);
in_order(root->left,sk,ans);
}
if(root->right)
{
sk.push(temp);
in_order(root->right,sk,ans);
}
if(!root->left&&!root->right)//子树为空
{
ans.push_back(temp);
}
}
vector<string> binaryTreePaths(TreeNode* root) {
stack<string> sk;
vector<string> ans;
if(!root)
return ans;
in_order(root,sk,ans);
for(int i=0;i<ans.size();i++)
{
ans[i] = ans[i].substr(0, ans[i].length() - 2);
}
return ans;
}
};