1#include <iostream>
2using namespace std;
3
4class Node { // A node holds its value and pointers to its two children
5private: // Private attributes: only the methods touch them
6 int value;
7 Node* left;
8 Node* right;
9public:
10 Node(int v) : value(v), left(nullptr), right(nullptr) {}
11 int getValue() const { return value; }
12 Node* getLeft() const { return left; }
13 Node* getRight() const { return right; }
14 void setLeft(Node* n) { left = n; }
15 void setRight(Node* n) { right = n; }
16};
17
18void preorder(Node* node) { // Traverses the subtree rooted at node
19 if (node == nullptr) return; // Base case: an empty subtree has nothing to visit
20 cout << node->getValue() << " "; // Visits the node: processes its value
21 preorder(node->getLeft()); // Traverses the left subtree
22 preorder(node->getRight()); // Traverses the right subtree
23} // Returns to the caller
24
25Node* insert(Node* root, int v) { // Inserts v into the search tree and returns the root
26 if (root == nullptr) return new Node(v); // Empty spot: the new node goes here
27 if (v < root->getValue()) // Smaller values go left and larger ones go right
28 root->setLeft(insert(root->getLeft(), v));
29 else
30 root->setRight(insert(root->getRight(), v));
31 return root;
32}
33
34Node* buildTree() { // Builds the tree by inserting the values one by one
35 int values[] = {60, 45, 85, 68, 21, 55, 32}; // The values of the tree shown, in insertion order
36 Node* root = nullptr;
37 for (int v : values) root = insert(root, v);
38 return root;
39}
40
41int main() {
42 Node* root = buildTree(); // The tree from the animation, already built
43 preorder(root); // First call, from main
44 cout << endl; // End of the traversal
45 return 0;
46}