#include <iostream> struct Node{ int key; Node* left = nullptr; Node* right = nullptr;…
- User
#include
struct Node{ int key; Node* left = nullptr; Node* right = nullptr; int left_child_ind; int right_child_ind; int height = 0; int balance; };
Node* Insert(Node* temp, int x, int l_ind, int r_ind) { if (temp == nullptr) { temp = new Node(); temp->key = x; temp->left_child_ind = l_ind; temp->right_child_ind = r_ind; } else if (x > temp->key) { temp->right = Insert(temp->right, x, l_ind, r_ind); } else { temp->left = Insert(temp->left, x, l_ind, r_ind); } return temp; }
void AddHeight(Node* temp) { if (temp == nullptr) { return; } AddHeight(temp->left); AddHeight(temp->right); int left_subtree_height = temp->left->height; int right_subtree_height = temp->right->height; if (left_subtree_height > right_subtree_height) { temp->height = left_subtree_height + 1; } else { temp->height = right_subtree_height + 1; } }
Node* RotateLeft(Node* temp) { Node* child = temp->left; temp->left = child->right; child->right = temp; return child; }
void PreorderTraversal(Node* root) { if (root != nullptr) { std::cout << root->key << " " << root->left_child_ind << " " << root->right_child_ind << '\n'; PreorderTraversal(root->left); PreorderTraversal(root->right); } }
int main() { int n; std::cin >> n; Node* root = new Node(); std::cin >> root->key >> root->left_child_ind >> root->right_child_ind; int key, left, right; for (int i = 1; i < n; ++i) { std::cin >> key >> left >> right; root = Insert(root, key, left, right); } std::cout << '1'; AddHeight(root); Node* temp = root; for (int i = 0; i < n; ++i) { temp->balance = temp->right->height - temp->left->height; } delete temp; if (root->left->balance != 1) { RotateLeft(root); } PreorderTraversal(root);
return 0;} if input is 7 -2 7 2 8 4 3 9 0 0 3 5 6 0 0 0 6 0 0 -7 0 0 it returns Process finished with exit code 139 (interrupted by signal 11: SIGSEGV)
- Assistant