Posts

Showing posts with the label AVL Tree

AVL Tree - All Operations Implementation

Image
  import java.util.*; // The node of the AVL tree // here we also maintain the height of each node so as to make height adjustments easier after  // the rotation in AVL tree class TreeNode{     int data;     int height;     TreeNode left;     TreeNode right;   // creating a node of AVL tree using constructor // Time Complexity - O(1) , Space Complexity - O(1)     TreeNode(int x){         this.data=x;         this.height=0;         this.left=null;         this.right=null;     }   } public class Main {   // Root of AVL tree     TreeNode root;   // Function to do a level order Traversal of AVL tree // Time Complexity - O(n) , Space Complexity - O(n) [As queue is used]    public void levelOrderTraversal() { //if AVL tree is empty   if (root == null) { ...

AVL Tree - Left Rotate and Right Rotate (in LL, RR, LR and RL conditions)

Image
  Hence Algorithm of left rotating a node in AVL tree : treeNode leftRotate(cdn){ treeNode NR = cdn.right; cdn.right = NR.left; // any left child of NR will be right child of cdn NR.left = cdn; / / After doing rotation, we have to adjust the height of cdn and NR now cdn.height = calculateHeight(cdn); NR.height = calculateHeight(NR); // finally we will return newRoot to the recursively calling function return NR; } The algorithm of right rotate is just the mirror image of this : treeNode rightRotate(cdn){ treeNode NR = cdn.left; cdn.left= NR.right; // any right child of NR will be left child of cdn NR.right= cdn; / / After doing rotation, we have to adjust the height of cdn and NR now cdn.height = calculateHeight(cdn); NR.height = calculateHeight(NR); // finally we will return newRoot to the recursive...