120 likes | 257 Views
AVL TREES. COP 3502. Deletion from an AVL Tree. First, do a normal Binary Search Tree Delete: If the node is a leaf, remove it. If it has 1 child, replace with its child If it has 2 children, replace with the largest in its left subtree ( inorder predecessor) and remove that node.
E N D
AVL TREES COP 3502
Deletion from an AVL Tree • First, do a normal Binary Search Tree Delete: • If the node is a leaf, remove it. • If it has 1 child, replace with its child • If it has 2 children, replace with the largest in its left subtree (inorder predecessor) and remove that node. • After deletion, retrace the path back up the tree, starting with the parent of the replacement, to the root, adjusting the balance factor as needed.
Deletion from an AVL Tree • In an insert there is at most one node that needs to be rebalanced. • But in a delete there may be multiple nodes to be rebalanced. • Technically only one rebalance that happens at a node, but once that happens it may affect the ancestral nodes.
Deletion Example • Delete 8: 32 16 48 8 24 40 56 28 36 44 52 60 58 62
Deletion Example 32 16 48 24 40 56 28 36 44 52 60 58 62
Deletion Example A 32 32 B 24 48 48 C 16 16 28 40 56 56 36 44 52 60 58 62
Deletion Example 48 32 56 24 52 60 40 58 62 16 16 28 36 44
Choosing A,B,C for Delete Restructuring • One thing that is more complicated about choosing the nodes A, B and C for the AVL Tree delete restructuring is that these nodes are NOT from the ancestral path followed from the origin of the delete. • Clearly, if a delete will cause an imbalance, it will be because the subtree that contains the deleted node has become too short. • Remember that the nodes A, B and C are always on the “longest” path to the bottom of the tree. • This means that when we find an imbalanced node after deleting, the node to the opposite side is guaranteed to be down the longer path. BF=2 30 A 15 45 B 10 35 50 C 32 55
Choosing A,B,C for Delete Restructuring • After labeling the first two nodes of A,B,C and there is still a choice between the right and left: • If one side is longer than the other, choose that side. • If the two sides are equal, go to the same side as the parent is to the grandparent. BF=2 30 B 45 A A 15 45 B 30 C 50 C 10 35 50 15 35 55 32 55 10 32
Choosing A,B,C for Delete Restructuring • The following situation is similar if we delete 50 from the following tree: BF=2 B C 15 30 A B 15 45 10 30 C A 50 10 17 5 17 45 5 20 20
AVL Tree Delete Examples • The most simple example is when a node from a tree with four nodes gets deleted. • Consider deleting 12 from the following tree: C 10 10 B C 8 A 5 12 B 8 A 5 10 C 8 B A 5
AVL Tree Delete Examples • Delete 30 from the following tree: BF=2 C 20 C 20 B 15 A 10 30 25 B 15 30 25 A 10 C 20 5 15 25 A B 10 5 12 25 12 5 12