-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
tree_inorder.cc
43 lines (38 loc) · 1.25 KB
/
tree_inorder.cc
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
#include <memory>
#include <stack>
#include <vector>
#include "binary_tree_node.h"
#include "test_framework/generic_test.h"
using std::stack;
using std::unique_ptr;
using std::vector;
vector<int> InorderTraversal(const unique_ptr<BinaryTreeNode<int>>& tree) {
vector<int> result;
struct NodeAndState {
const BinaryTreeNode<int>* node;
bool left_subtree_traversed;
};
stack<NodeAndState> in_process(
{{tree.get(), /*left_subtree_traversed=*/false}});
while (!empty(in_process)) {
auto [node, left_subtree_traversed] = in_process.top();
in_process.pop();
if (node) {
if (left_subtree_traversed) {
result.emplace_back(node->data);
} else {
in_process.push({node->right.get(), /*left_subtree_traversed=*/false});
in_process.push({node, /*left_subtree_traversed=*/true});
in_process.push({node->left.get(),
/*left_subtree_traversed=*/false});
}
}
}
return result;
}
int main(int argc, char* argv[]) {
std::vector<std::string> args{argv + 1, argv + argc};
std::vector<std::string> param_names{"tree"};
return GenericTestMain(args, "tree_inorder.cc", "tree_inorder.tsv",
&InorderTraversal, DefaultComparator{}, param_names);
}