1
+ #include < iostream>
2
+ #include < vector>
3
+ using namespace std ;
4
+
5
+ template <typename T>
6
+ struct Node
7
+ {
8
+ T value;
9
+ Node *left{nullptr }, *right{nullptr }, *parent{nullptr };
10
+
11
+ Node (T value) : value(value) {}
12
+
13
+ Node (T value, Node<T> *left, Node<T> *right) : value(value), left(left), right(right) {
14
+ left->parent = right->parent = this ;
15
+ }
16
+
17
+ void preorder_traversal_impl (Node<T>* current, vector<Node<T>*>& result)
18
+ {
19
+ result.push_back (current);
20
+ if (current->left )
21
+ {
22
+ preorder_traversal_impl (current->left , result);
23
+ }
24
+ if (current->right )
25
+ {
26
+ preorder_traversal_impl (current->right , result);
27
+ }
28
+ }
29
+
30
+ // traverse the node and its children preorder
31
+ // and put all the results into `result`
32
+
33
+ // this interface does not expose it is a tree
34
+ void preorder_traversal (vector<Node<T>*>& result)
35
+ {
36
+ preorder_traversal_impl (this , result);
37
+ }
38
+ };
39
+
40
+ #include " gtest/gtest.h"
41
+
42
+ // #include "helpers/iohelper.h"
43
+
44
+ // #include "exercise.cpp"
45
+
46
+ namespace {
47
+
48
+ class Evaluate : public ::testing::Test {};
49
+
50
+ TEST_F (Evaluate, ExampleTest) {
51
+ Node<char > c{' c' };
52
+ Node<char > d{' d' };
53
+ Node<char > e{' e' };
54
+ Node<char > b{' b' , &c, &d};
55
+ Node<char > a{' a' , &b, &e};
56
+
57
+ vector<Node<char >*> result;
58
+ a.preorder_traversal (result);
59
+
60
+ ostringstream oss;
61
+ for (auto n : result)
62
+ oss << n->value ;
63
+ ASSERT_EQ (" abcde" , oss.str ());
64
+ }
65
+
66
+ } // namespace
67
+
68
+ int main (int ac, char * av[])
69
+ {
70
+ // ::testing::GTEST_FLAG(catch_exceptions) = false;
71
+ testing::InitGoogleTest (&ac, av);
72
+ return RUN_ALL_TESTS ();
73
+ }
0 commit comments