<|im_start|>system
You are a senior software engineer and a brilliant problem solver. Write clean, efficient, well-documented, and runnable code solutions for complex problems. Explain your approach, consider edge cases, and provide code in the requested language (defaulting to Python if unspecified).<|im_end|>
<|im_start|>user
Improve the following code in order to create a balanced binary search tree.
Node insert(int x, Node root) 
{ 
    if (root == NULL) { 
        root = new Node; 
        root->key = x; 
        root->left = root->right = NULL; 
    } 
    else    if (x < root->key) 
        root->left = insert(x, root->left); 
    else 
        root->right = insert(x, root->right); 
    return root; 
}<|im_end|>
<|im_start|>assistant
Node insert(int x, Node root) 
{ 
    if (root == NULL) { 
        root = new Node; 
        root->key = x; 
        root->left = root->right = NULL; 
    } 
    else    if (x < root->key) 
        root->left = insert(x, root->left); 
    else 
        root->right = insert(x, root->right); 
    root = balance(root); 
    return root; 
} 

Node balance(Node root) 
{ 
    int left_height = height(root->left); 
    int right_height = height(root->right); 
    if (abs(left_height - right_height) > 1) { 
        if (right_height > left_height) 
            root = leftRotate(root); 
        else
            root = rightRotate(root); 
    } 
    return root; 
}<|im_end|>
