static AVLNode rebalancing(AVLNode root) { root.ht = Math.max(height(root.left), height(root.right)) + 1; int bf = height(root.left) - height(root.right); if (bf > 1) { bf = height(root.left.left) - height(root.left.right); if (bf < 0) { root.left = rotate(root.left, true); } root = rotate(root, false); } else if (bf < -1) { bf = height(root.right.left) - height(root.right.right); if (bf > 0) { root.right = rotate(root.right, false); } root = rotate(root, true); } return root; }
static AVLNode rotate(AVLNode root, boolean isLeft) { if (isLeft) { AVLNode right = root.right; root.right = right.left; right.left = root; root.ht = Math.max(height(root.left), height(root.right)) + 1; root = right; root.ht = Math.max(height(root.left), height(root.right)) + 1; } else { AVLNode left = root.left; root.left = left.right; left.right = root; root.ht = Math.max(height(root.left), height(root.right)) + 1; root = left; root.ht = Math.max(height(root.left), height(root.right)) + 1; } return root; }
// https://www.hackerrank.com/challenges/self-balancing-tree public AVLNode insert(AVLNode root, int val) { if (root == null) { AVLNode node = new AVLNode(); node.val = val; node.ht = 0; return node; } if (root.val > val) { root.left = insert(root.left, val); } else { root.right = insert(root.right, val); } return rebalancing(root); }