-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path94.cpp
72 lines (58 loc) · 1.55 KB
/
94.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
70
71
72
#include <stack>
#include <vector>
#include <iostream>
using namespace std;
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:
vector<int> inorderTraversal(TreeNode *root) {
stack<TreeNode *> stack = {};
vector<int> res = {};
stack.push(root);
while (!stack.empty()) {
auto top = stack.top();
if (top == nullptr) {
stack.pop();
continue;
}
auto left = top->left;
auto right = top->right;
if (left != nullptr) {
if (left->val > -101) {
stack.push(left);
continue;
}
}
if (top->val > -101) {
res.push_back(top->val);
top->val = -101;
}
if (right != nullptr) {
if (right->val > -101) {
stack.push(right);
continue;
}
}
stack.pop();
}
return res;
}
};
int main(int argc, char const *argv[]) {
auto root = new TreeNode(3, new TreeNode(1, nullptr, new TreeNode(2)), nullptr);
Solution s;
auto ret = s.inorderTraversal(root);
for (auto r : ret) {
cout << r << endl;
}
return 0;
}