AVL tree is a balanced binary search tree where the difference between heights of two sub trees is maximum 1.
Here all nodes have only right children. To search a value in this tree, we need upto 7 iterations, which is O(n).
So this tree is very very inefficient.
One way of making the tree efficient is to, balance the tree and make sure that height of two branches of each node are almost equal.
So we have performed single left rotation on the node.
When a node is inserted to an AVL tree, it needs a either a single rotation or a double rotation. But if a node is deleted from AVL tree, then the nodes need to be rotated successively until root is reached.
Why balanced tree
A binary tree is good data structure because search operation here is of the order of O(logn). But this is true if the tree is balanced - which means the left and right subtrees are almost equal in height. If not balanced, search operation will take longer.
In worst case, if the tree has only one branch, then search is of the order O(n). Look at this example.
So this tree is very very inefficient.
One way of making the tree efficient is to, balance the tree and make sure that height of two branches of each node are almost equal.
Height of a node
Height of a node is the distance between the node and its extreme child.
In the above a diagram, height of 37 is 3 and height of left child of 37 is 0 and right child of 37 is 2.
Balancing a node
A node is rotated, in such a way that order of the elements is retained, but the node becomes more balanced.
In the above example, if we rotate the node containing 38 and make 37 as left child of 38, the tree is still in correct order, but is better balanced.
When a node is inserted to an AVL tree, it needs a either a single rotation or a double rotation. But if a node is deleted from AVL tree, then the nodes need to be rotated successively until root is reached.
Comments
Post a Comment