Binary Tree Visualiser BST & AVL · by Tanmay Bohra
SPEED
Ready — enter a value and click INSERT
tanmay-bohra.dev
1// AVL Tree · Java 17 · Tanmay Bohra
2// Self-balancing Binary Search Tree
3 
4public class AVLTree {
5 
6// ── Node ─────────────────────────────────
7static class Node {
8int key, height;
9Node left, right;
10Node(int k) {
11this.key = k;
12this.height = 1;
13}
14}
15 
16// ── Helpers ──────────────────────────────
17int height(Node n) {
18return n == null ? 0 : n.height;
19}
20 
21int bf(Node n) {
22return n == null ? 0
23: height(n.left) - height(n.right);
24}
25 
26void updateHeight(Node n) {
27n.height = 1 + Math.max(
28height(n.left), height(n.right));
29}
30 
31// ── BST insert ────────────────────────────
32Node bstInsert(Node nd, int k) {
33if (nd == null)
34return new Node(k);
35if (k < nd.key)
36nd.left = bstInsert(nd.left, k);
37else if (k > nd.key)
38nd.right = bstInsert(nd.right, k);
39return nd;
40}
41 
42// ── rotateRight (fixes LL) ───────────────
43Node rotateRight(Node y) {
44Node x = y.left;
45Node T2 = x.right;
46x.right = y;
47y.left = T2;
48updateHeight(y);
49updateHeight(x);
50return x;
51}
52 
53// ── rotateLeft (fixes RR) ───────────────
54Node rotateLeft(Node x) {
55Node y = x.right;
56Node T2 = y.left;
57y.left = x;
58x.right = T2;
59updateHeight(x);
60updateHeight(y);
61return y;
62}
63 
64// ── avlInsert (BST + rebalance) ──────────
65Node avlInsert(Node nd, int k) {
66if (nd == null)
67return new Node(k);
68if (k < nd.key)
69nd.left = avlInsert(nd.left, k);
70else if (k > nd.key)
71nd.right = avlInsert(nd.right, k);
72else return nd;
73 
74updateHeight(nd);
75int b = bf(nd);
76 
77// LL — single right rotation
78if (b > 1 && k < nd.left.key)
79return rotateRight(nd);
80// RR — single left rotation
81if (b < -1 && k > nd.right.key)
82return rotateLeft(nd);
83// LR — left then right
84if (b > 1 && k > nd.left.key) {
85nd.left = rotateLeft(nd.left);
86return rotateRight(nd);
87}
88// RL — right then left
89if (b < -1 && k < nd.right.key) {
90nd.right = rotateRight(nd.right);
91return rotateLeft(nd);
92}
93return nd;
94}
95}
Nodes
0
Height
Mode
BST
Balanced