-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0094.binary_tree_inorder_traversal.cpp
More file actions
61 lines (49 loc) · 1.17 KB
/
0094.binary_tree_inorder_traversal.cpp
File metadata and controls
61 lines (49 loc) · 1.17 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
#include <iostream>
#include <vector>
#include <stack>
#include "leetcode.h"
using std::vector, std::stack;
vector<int> inorder_traversal(TreeNode *root)
{
vector<int> res;
stack<TreeNode*> stk;
while (root != nullptr || !stk.empty()) {
while (root != nullptr) {
stk.push(root);
root = root->left;
}
root = stk.top();
stk.pop();
res.push_back(root->val);
root = root->right;
}
return res;
}
vector<int> _inorder_traversal(TreeNode *root)
{
vector<int> res;
auto traversal = [&res](auto&& self, TreeNode *cur) -> void {
if (cur == nullptr) return ;
self(self, cur->left);
res.push_back(cur->val);
self(self, cur->right);
};
traversal(traversal, root);
return res;
}
int main () {
#ifdef LOCAL
freopen("0094.in", "r", stdin);
#endif
int n = 0;
while (std::cin >> n) {
vector<int> nums(n, 0);
for (int i = 0; i < n; ++i) {
std::cin >> nums[i];
}
TreeNode *head = build_tree(nums);
vector<int> res = inorder_traversal(head);
std::cout << res << std::endl;
}
return 0;
}