{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}


We could use a sorted array to do all these in o1

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: 31/5331 Tree-Insert(T, z) n Insert z into tree T, and resulting tree still binary search tree 15 6 3 2 18 7 17 20 13 4 Tree-Insert(T, 8) Use Tree-search ! 9 CSE 780 Algorithms Pseudocode n Tree-insert(T, z) y = Nil, x = root[T] while (x ≠ Nil) do y=x Locate potential parent y of z. if ( z.key < x.key ) then x = x.left else x = x.right z.parent = y if (y = Nil) then root[T] = z Time: O(h) else if (z.key < y.key) then y.left = z else y.right = z CSE 780 Algorithms Build Binary Search Tree CSE 780 Algorithms Deletion 15 6 3 2 18 7 17 13 4 9 20 16 23 delete 17?? delete15 6 3 7 4 CSE 780 Algorithms Three Cases for Deleting z n n Case 1: Leaf node Case 2: Has only one child n n Replace z with its child Case 3: Has both children n Find its successor y n n n y cannot have left child! replacing y with its right child! Replace z with y The “replacement’’ is implemented by the transplant operation CSE 780 Algorithms Transplant Operation CSE 2331/5331 Case 3: More Detailed View n n n Goal: delete node z Let y be the successor of z Case-(3.1) n n y is the right child of z Then replace z by y CSE 2331/5331 Case 3: cont. n Case (3.b): n n y is not the right child of z First replace y by its own right child, and then replace z b y y. CSE 2331/5331 Delete together cover Cases 1 & 2. Time complexity: O(h) CSE 2331/5331 An Exercise Delete I ? Delete G ? Delete K ? Delete B ? CSE 2331/5331 Remarks n n n All complexity depends on height h h = (lg n), h = (n) To guarantee performance: n n Balanced tree ! Randomly build a tree n n Expected height is O(lg n) Still problem: future insertions … CSE 780 Algorithms...
View Full Document

{[ snackBarMessage ]}

Ask a homework question - tutors are online