Algo-Sim › Binary Trees & BST

AVL Tree Insert

Hard · Binary Trees & BST · step through it in Java, Python and C++ on your own input

Insert values into a self-balancing BST: update heights on the way back up and fix any node whose balance leaves −1 … +1 with one or two rotations.

Problem

Insert values one at a time into an initially empty AVL tree: a binary search tree in which every node’s left and right subtree heights differ by at most 1. After each insert, rebalance with rotations. Ignore duplicates. Return the final tree’s preorder (which, for a BST, fixes its shape).

Constraints

Edge cases to test

Follow-up questions

Why is an AVL tree O(log n) tall?
The fewest nodes at height h is N(h) = N(h − 1) + N(h − 2) + 1, a Fibonacci recurrence, so h ≤ 1.44 · log₂ n.
How does a red–black tree differ?
It balances more loosely (no red node has a red child; every path has the same black count), so height ≤ 2 · log₂(n + 1) and inserts need at most 2 rotations. Java’s TreeMap and C++’s std::map use it.
What about deletion?
Delete as in a BST, then walk back up rebalancing. Unlike insertion, a deletion can need a rotation at every level: still O(log n).

Solution

Java

public List<Integer> buildAvl(int[] values) {
    AvlNode root = null;
    for (int v : values) root = insert(root, v);
    List<Integer> out = new ArrayList<>();
    preorder(root, out);
    return out;
}

private AvlNode insert(AvlNode node, int v) {
    if (node == null) return new AvlNode(v);
    if (v < node.val) node.left = insert(node.left, v);
    else if (v > node.val) node.right = insert(node.right, v);
    else return node;
    node.height = 1 + Math.max(h(node.left), h(node.right));
    int balance = h(node.left) - h(node.right);
    if (balance > 1 && v < node.left.val) return rotateRight(node);
    if (balance < -1 && v > node.right.val) return rotateLeft(node);
    if (balance > 1) {
        node.left = rotateLeft(node.left);
        return rotateRight(node);
    }
    if (balance < -1) {
        node.right = rotateRight(node.right);
        return rotateLeft(node);
    }
    return node;
}

private AvlNode rotateRight(AvlNode y) {
    AvlNode x = y.left;
    y.left = x.right;
    x.right = y;
    y.height = 1 + Math.max(h(y.left), h(y.right));
    x.height = 1 + Math.max(h(x.left), h(x.right));
    return x;
}

private AvlNode rotateLeft(AvlNode x) {
    AvlNode y = x.right;
    x.right = y.left;
    y.left = x;
    x.height = 1 + Math.max(h(x.left), h(x.right));
    y.height = 1 + Math.max(h(y.left), h(y.right));
    return y;
}

private int h(AvlNode n) {
    return n == null ? 0 : n.height;
}

private void preorder(AvlNode n, List<Integer> out) {
    if (n == null) return;
    out.add(n.val);
    preorder(n.left, out);
    preorder(n.right, out);
}

static class AvlNode {
    int val, height = 1;
    AvlNode left, right;
    AvlNode(int val) { this.val = val; }
}

Python

class AvlNode:
    def __init__(self, val):
        self.val, self.height = val, 1
        self.left = self.right = None


def h(n):
    return n.height if n else 0


def rotate_right(y):
    x = y.left
    y.left = x.right
    x.right = y
    y.height = 1 + max(h(y.left), h(y.right))
    x.height = 1 + max(h(x.left), h(x.right))
    return x


def rotate_left(x):
    y = x.right
    x.right = y.left
    y.left = x
    x.height = 1 + max(h(x.left), h(x.right))
    y.height = 1 + max(h(y.left), h(y.right))
    return y


def insert(node, v):
    if not node:
        return AvlNode(v)
    if v < node.val:
        node.left = insert(node.left, v)
    elif v > node.val:
        node.right = insert(node.right, v)
    else:
        return node
    node.height = 1 + max(h(node.left), h(node.right))
    balance = h(node.left) - h(node.right)
    if balance > 1 and v < node.left.val:
        return rotate_right(node)
    if balance < -1 and v > node.right.val:
        return rotate_left(node)
    if balance > 1:
        node.left = rotate_left(node.left)
        return rotate_right(node)
    if balance < -1:
        node.right = rotate_right(node.right)
        return rotate_left(node)
    return node


def build_avl(values):
    root = None
    for v in values:
        root = insert(root, v)
    out = []

    def preorder(n):
        if n:
            out.append(n.val)
            preorder(n.left)
            preorder(n.right)

    preorder(root)
    return out

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
    struct AvlNode {
        int val, height = 1;
        AvlNode *left = nullptr, *right = nullptr;
        AvlNode(int val) : val(val) {}
    };

    int h(AvlNode *n) { return n == nullptr ? 0 : n->height; }

    AvlNode *rotateRight(AvlNode *y) {
        AvlNode *x = y->left;
        y->left = x->right;
        x->right = y;
        y->height = 1 + max(h(y->left), h(y->right));
        x->height = 1 + max(h(x->left), h(x->right));
        return x;
    }

    AvlNode *rotateLeft(AvlNode *x) {
        AvlNode *y = x->right;
        x->right = y->left;
        y->left = x;
        x->height = 1 + max(h(x->left), h(x->right));
        y->height = 1 + max(h(y->left), h(y->right));
        return y;
    }

    AvlNode *insert(AvlNode *node, int v) {
        if (node == nullptr)
            return new AvlNode(v);
        if (v < node->val)
            node->left = insert(node->left, v);
        else if (v > node->val)
            node->right = insert(node->right, v);
        else
            return node;
        node->height = 1 + max(h(node->left), h(node->right));
        int balance = h(node->left) - h(node->right);
        if (balance > 1 && v < node->left->val)
            return rotateRight(node);
        if (balance < -1 && v > node->right->val)
            return rotateLeft(node);
        if (balance > 1) {
            node->left = rotateLeft(node->left);
            return rotateRight(node);
        }
        if (balance < -1) {
            node->right = rotateRight(node->right);
            return rotateLeft(node);
        }
        return node;
    }

    void preorder(AvlNode *n, vector<int> &out) {
        if (n == nullptr)
            return;
        out.push_back(n->val);
        preorder(n->left, out);
        preorder(n->right, out);
    }

  public:
    vector<int> buildAvl(vector<int> &values) {
        AvlNode *root = nullptr;
        for (int v : values)
            root = insert(root, v);
        vector<int> out = {};
        preorder(root, out);
        return out;
    }
};

More Binary Trees & BST problems