620 likes | 637 Views
Binary Search Trees. Lecture 6 Asst. Prof. Dr. İlker Kocabaş. Binary search tree sort. Binary-search-tree property. Binary-search-tree property. Binary Search Tree can be implemented as a linked data structure in which each node is an object with three pointer fields.
E N D
Binary Search Trees Lecture 6 Asst. Prof. Dr. İlker Kocabaş
Binary-search-tree property • Binary Search Tree can be implemented as a linked data structure in which each node is an object with three pointer fields. • The three pointer fields left, right and p point to the nodes corresponding to the left child, right child and the parent respectively. • NIL in any pointer field signifies that there exists no corresponding child or parent. • The root node is the only node in the BTS structure with NIL in its p field.
Inorder-tree walk During this type of walk, we visit the root of a subtree between the left subtree visit and right subtree visit.
Preorder-tree walk In this case we visit the root node before the nodes in either subtree.
Postorder-tree walk We visit the root node after the nodes in its subtrees.
1 2 6 Sorting by binary-search-tree 1 2 3 1 2 2 6 1 NIL • PRINT 2 4 7 3 NIL 3 PRINT 3 4 5 2 8 • 1 • NIL • PRINT 5 • NIL 5 3 PRINT 6 4 • 1 • NIL • PRINT 7 • 4 7 7 • 1 • NIL • PRINT 8 • NIL 8
Searching for a key 15 18 6 7 3 17 20 4 2 Search for 13 13 9
Searching for minimum 15 18 6 7 3 17 20 4 2 13 Minimum 9
Searching for maximum 15 18 6 7 3 17 20 Maximum 4 2 13 9
Searching for successor The successor of a node x is the node with the smallest key greather than key[x]
Searching for successor 15 18 6 7 3 17 20 Successor of 15 4 2 13 9 Case 1: The right subtree of node xis nonempty
Searching for successor Successor of 13 15 18 6 7 3 17 20 4 2 13 9 Case 2: The right subtree of node xis empty
Searching for successor 15 Successor of 4 search until y.left = x 18 6 7 3 17 20 4 2 13 9 Case 2: The right subtree of node xis empty
Searching for successor Go upper until y.left = x
Insertion 12 18 5 9 2 15 19 13 17 Inserting an item with key 13
Deletion 15 16 5 5 12 3 2 20 13 z 10 23 18 6 7 Deleting an item with key 13 (z has no children)
Deletion 15 16 5 5 12 3 2 20 10 23 18 6 7 Deleting an item with key 13 (z has no children)
Deletion 15 16 z 5 5 12 3 2 20 13 10 23 18 6 7 Deleting a node with key 16 (z has only one child )
Deletion 15 5 5 20 12 3 2 23 18 13 10 6 7 Deleting a node with key 16 (z has only one child )
Deletion 15 z 5 16 5 12 3 2 20 10 13 18 23 6 y 7 Deleting a node with key 5 (6 successor of 5)(z has two children)
Deletion 15 6 y z 5 16 5 12 3 2 20 10 23 18 7 Deleting a node with key 5 (z has two children)
Deletion 15 6 16 5 12 3 2 20 10 23 18 7 Deleting a node with key 5 (z has two children)
Analysis of BST sort The expected time to built the tree is asymptotically the same as the running time of quicksort