-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconstruct-string-from-binary-tree.cpp
More file actions
48 lines (41 loc) · 1.19 KB
/
construct-string-from-binary-tree.cpp
File metadata and controls
48 lines (41 loc) · 1.19 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
/**
https://leetcode.com/problems/construct-string-from-binary-tree/submissions/
* 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:
string tree2str(TreeNode* t) {
if (nullptr == t)
return "";
stack<TreeNode*> s;
s.push(t);
set<TreeNode*> visited;
string res="";
while ( !s.empty())
{
t = s.top();
cout<<"s.top "<<t->val<<endl;
if (visited.find(t) != visited.end())
{
s.pop();
res.append(")");
}else{
visited.insert(t);
res.append("("+to_string(t->val));
if (t->left == nullptr && t->right != nullptr)
res.append("()");
if (t->right != nullptr)
s.push(t->right);
if (t->left != nullptr)
s.push(t->left);
}
}
return res.substr(1, res.size()-1);
}
};