1#include <iostream>
2using namespace std;
3
4class Node { // Um nó guarda seu valor e ponteiros para seus dois filhos
5private: // Atributos privados: só os métodos acessam
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) { // Percorre a subárvore com raiz em node
19 if (node == nullptr) return; // Caso base: uma subárvore vazia não tem nada a visitar
20 cout << node->getValue() << " "; // Visita o nó: processa seu valor
21 preorder(node->getLeft()); // Percorre a subárvore esquerda
22 preorder(node->getRight()); // Percorre a subárvore direita
23} // Retorna ao chamador
24
25Node* insert(Node* root, int v) { // Insere v na árvore de busca e devolve a raiz
26 if (root == nullptr) return new Node(v); // Posição vazia: o novo nó fica aqui
27 if (v < root->getValue()) // Valores menores vão para a esquerda e maiores para a direita
28 root->setLeft(insert(root->getLeft(), v));
29 else
30 root->setRight(insert(root->getRight(), v));
31 return root;
32}
33
34Node* buildTree() { // Constrói a árvore inserindo os valores um a um
35 int values[] = {60, 45, 85, 68, 21, 55, 32}; // Os valores da árvore exibida, na ordem de inserção
36 Node* root = nullptr;
37 for (int v : values) root = insert(root, v);
38 return root;
39}
40
41int main() {
42 Node* root = buildTree(); // A árvore da animação, já construída
43 preorder(root); // Primeira chamada, a partir de main
44 cout << endl; // Fim do percurso
45 return 0;
46}