AfanasevGad7

This is a task for our favourite professor
git clone git://git.stellar-nexus.ru/AfanasevGad7
Log | Files | Refs

commit c4e292b6048e1bd0bdd47fa73238906551c51c0b
parent 13eb3a9377c3daec4a441e257baaeaeceaee4d30
Author: Plat <plat@stellar-nexus.ru>
Date:   Thu, 23 Oct 2025 19:51:14 +0000

Added balance2 function

Diffstat:
Mfinal_solution.cpp | 35++++++++++++++++++++++++++++++++++-
1 file changed, 34 insertions(+), 1 deletion(-)

diff --git a/final_solution.cpp b/final_solution.cpp @@ -38,7 +38,7 @@ int main() { { std::cin >> k; add(k, root); - root = balance(root); + root = balance2(root); } // value_node = search(root, 'int value from input')); @@ -141,6 +141,15 @@ get_height(Node* root) return r; } +inline int +get_balance_factor(Node* root) +{ + if (!root) + return 0; + + return get_height(root->left) - (get_geight(root->right); +} + Node* right_turn(Node* root) @@ -182,6 +191,30 @@ balance(Node* root) return root; } +Node* +balance2(Node* root) +{ + if (!root) + return nullptr; + + int bf = get_balance_factor(root); + + + if (bf > 1) { + if (get_balance_factor(root->left) < 0) + root->left = left_turn(root->left); + return right_turn(root) + } + + if (bf < -1) { + if (get_balance_factor(root->left) > 0) + root->right = right_turn(root->right); + return left_turn(root) + } + + return root; +} + Node* search(Node* root, int val)