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
- 1 ≤ values.length ≤ 10⁴
- Height stays ≤ 1.44 · log₂(n + 2)
- O(log n) per insert, at most one single or double rotation
Edge cases to test
- Sorted input (a plain BST would become a chain)
- Duplicates
- One value
- A double rotation (LR or RL)
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 outC++
#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
- Preorder Traversal (Recursive) (Easy)
- Inorder Traversal (Recursive) (Easy)
- Postorder Traversal (Recursive) (Easy)
- Preorder Traversal (Iterative) (Easy)
- Inorder Traversal (Iterative) (Easy)
- Postorder Traversal (Iterative) (Easy)
- Binary Tree Level Order Traversal (Medium)
- Binary Tree Zigzag Level Order Traversal (Medium)
- Binary Tree Right Side View (Medium)
- Vertical Order Traversal of a Binary Tree (Hard)
- Maximum Depth of Binary Tree (Easy)
- Diameter of Binary Tree (Easy)
- Balanced Binary Tree (Easy)
- Invert Binary Tree (Easy)
- Flatten Binary Tree to Linked List (Medium)
- Same Tree (Easy)
- Symmetric Tree (Easy)
- Subtree of Another Tree (Easy)
- Path Sum (Easy)
- Path Sum II (Medium)
- Path Sum III (Medium)
- Count Good Nodes in Binary Tree (Medium)
- Lowest Common Ancestor of a Binary Tree (Medium)
- Kth Ancestor of a Tree Node (Hard)
- All Nodes Distance K in Binary Tree (Medium)
- Validate Binary Search Tree (Medium)
- Search in a Binary Search Tree (Easy)
- Insert into a Binary Search Tree (Medium)
- Delete Node in a BST (Medium)
- Kth Smallest Element in a BST (Medium)
- Binary Search Tree Iterator (Medium)
- Convert Sorted Array to Binary Search Tree (Easy)
- Construct Binary Tree from Preorder and Inorder Traversal (Medium)
- Binary Tree Maximum Path Sum (Hard)
- Serialize and Deserialize Binary Tree (Hard)