#include <iostream> #include <algorithm> struct Node { int data; int left; int right;…
- User
#include #include
struct Node { int data; int left; int right; int height; };
int Height(int index, Node arr[]) { if (index == -1) return 0; if (arr[index].height > 0) return arr[index].height;
arr[index].height = 1 + std::max(Height(arr[index].left, arr), Height(arr[index].right, arr)); return arr[index].height; }
int Balance(int index, Node arr[]) { if (index == -1) return 0; return Height(arr[index].right, arr) - Height(arr[index].left, arr); }
void UpdateHeight(int index, Node arr[]) { if (index == -1) return;
arr[index].height = 1 + std::max(Height(arr[index].left, arr), Height(arr[index].right, arr)); }
int RightRotate(int y, Node arr[]) { int x = arr[y].left; int T2 = arr[x].right;
arr[x].right = y; arr[y].left = T2;
UpdateHeight(y, arr); UpdateHeight(x, arr);
return x; }
int LeftRotate(int x, Node arr[]) { int y = arr[x].right; int T2 = arr[y].left;
arr[y].left = x; arr[x].right = T2;
UpdateHeight(x, arr); UpdateHeight(y, arr);
return y; }
void print(int index, Node arr[], int n) { if (index == -1) return;
// +1 на входе, так как индексы начинаются с 1, а не с 0 std::cout << arr[index].data << ' '; std::cout << ((arr[index].left == -1) ? 0 : arr[index].left + 1) << ' '; std::cout << ((arr[index].right == -1) ? 0 : arr[index].right + 1) << '\n'; // Печать левого и правого ребенка узла if(arr[index].left != -1) { print(arr[index].left, arr, n); } if(arr[index].right != -1) { print(arr[index].right, arr, n); }}
int main() { int n; std::cin >> n;
Node arr[n]; for (int i = 0; i < n; ++i) { std::cin >> arr[i].data; std::cin >> arr[i].left >> arr[i].right; arr[i].left -= 1; arr[i].right -= 1; arr[i].height = 0; }
for (int i = 0; i < n; ++i) { Height(i, arr); }
int root = 0; if (Balance(arr[root].right, arr) < 0) { arr[root].right = RightRotate(arr[root].right, arr); }
root = LeftRotate(root, arr);
std::cout << n << std::endl;
print(root, arr, n);
return 0; }
ты можешь добавить в структуру переменную которая показывает номер узла(нумерация по уровням слева направо)
- Assistant
Конечно, вы можете добавить дополнительное поле в структуру
Nodeдля хранения номера узла. Обычно для хранения подобного числового идентификатора используется типint. Ниже номер узла будет называться , который будет уникально идентифицировать каждый узел дерева и номеровать их слева направо по уровням. - User
Для балансировки АВЛ-дерева при операциях вставки и удаления производятся левые и правые повороты. Левый поворот в вершине производится, когда баланс этой вершины больше 1, аналогично, правый поворот производится при балансе, меньшем 1.
Существует два разных левых (как, разумеется, и правых) поворота: большой и малый левый поворот.
Малый левый поворот осуществляется следующим образом:
{скоро тут будет иллюстрация}
Заметим, что если до выполнения малого левого поворота был нарушен баланс только корня дерева, то после его выполнения все вершины становятся сбалансированными, за исключением случая, когда у правого ребенка корня баланс до поворота равен 1. В этом случае вместо малого левого поворота выполняется большой левый поворот, который осуществляется так:
- Assistant
- User
#include
struct Node { int data; Node* left; Node* right; };
Node* NewNode(int data) { Node* temp = new Node; temp->data = data; temp->left = temp->right = nullptr;
return temp;}
Node* Insert(Node* node, int data) { if (node == nullptr) return NewNode(data);
if (data < node->data) node->left = Insert(node->left, data); else if (data > node->data) node->right = Insert(node->right, data);
return node; }
Node* BuildTree(int arr[], int size) { Node *root = nullptr; for(int i=0; i<size; i++){ root = Insert(root,arr[i]); } return root; }
void PrintRightNodes(Node* root, int lvl, int &max_lvl) { if (root == nullptr) return;
- Assistant
- User
#include #include
struct Node { int data; Node* left; Node* right; };
Node* NewNode(int data) { Node* temp = new Node; temp->data = data; temp->left = temp->right = nullptr; return temp; }
void PrintInOrder(Node* node) { if (node == nullptr) { return; } PrintInOrder(node->left); std::cout << node->data << " "; PrintInOrder(node->right); }
int main() { int n; std::cin >> n; std::vector<Node*> nodes(n, nullptr);
// Сначала создаём все узлы без связей. for (int i = 0; i < n; ++i) { int data, left, right; std::cin >> data >> left >> right; nodes[i] = NewNode(data); // Сохраняем индексы детей как “data” в левом и правом указателе. // Используем “data” для хранения индексов, потому что связи устанавливаются позже. nodes[i]->left = reinterpret_cast<Node*>(left); nodes[i]->right = reinterpret_cast<Node*>(right); } // Теперь устанавливаем связи между узлами. for (int i = 0; i < n; ++i) { int leftIndex = reinterpret_cast<intptr_t>(nodes[i]->left) - 1; // Индексация с 0. int rightIndex = reinterpret_cast<intptr_t>(nodes[i]->right) - 1; // Индексация с 0. if (leftIndex >= 0) { nodes[i]->left = nodes[leftIndex]; } else { nodes[i]->left = nullptr; } if (rightIndex >= 0) { nodes[i]->right = nodes[rightIndex]; } else { nodes[i]->right = nullptr; } } // Теперь корневой узел находится в nodes[0]. PrintInOrder(nodes[0]); // Освобождаем память for (Node* node : nodes) { delete node; } return 0; - Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.