1 Lecture 21: Binary Search Tree delete etc. operations Lecturer: Santokh Singh CompSci 105 SS 2005 Principles of Computer Science
2 As with a Binary Tree, except Root node has a special data element called a key Nodes in left subtree have keys < the root’s key Nodes in right subtree have keys > the root’s key. Binary Search Trees (BSTs) K Textbook, p >K <K
3 Searching M BQ JUO
4 Add as a leaf M BQ JUO
5 Draw the BST that results from inserting the values 4, 3, 2, 7, 5, 6 in order. Draw as many different BST’s shapes as possible with nodes A, B, and C. B CA C B A C A B A B C A C B
6 Inorder Traversal void printTree( TreeNode root) if ( root != null ) printTree( root.getLeft () ); println(root.getRootItem()); printTree( root.getRight() ); } Textbook, p. 434 M BQ JUO
7 Inorder Traversal void printTree( TreeNode root) if ( root != null ) printTree( root.getLeft () ); println(root.getRootItem()); printTree( root.getRight() ); } B CA C B A C A B A B C A C B
8 Preorder Traversal void printTree( TreeNode root) if ( root != null ) println( root.getRootItem()); printTree( root.getLeft () ); printTree( root.getRight() ); } Textbook, p. 433 M BQ JUO
9 Postorder Traversal void printTree( TreeNode root) if ( root != null ) printTree( root.getLeft () ); printTree( root.getRight() ); println(root.getRootItem()); } Textbook, p. 434 M BQ JUO
10 Exercise For each of the trees below, what is the preorder traversal? What is the postorder traversal? B CA C B A C A B A B C A C B
11 BST Delete M BQ JUO
12 BST Delete Delete( TreeNode root, Key searchKey) { if ( root==null ) // item not found else if ( root.getKey == searchKey ) // Delete Root else // search in appropriate subtree if ( searchKey < root.getKey()) // delete from left subtree else // delete from right subtree } Textbook, p
13 BST Delete M BQ JUO
14 Deleting the root M M B J M Q U O M BQ U O J root No children No right child No left child Two children Textbook, p. 462
15 Deleting the root BQ U O J root M BQ U O J Textbook, p , Java Code p
16 Deleting the root BQ U O J root M BQ U O J Textbook, p , Java Code p
17 Deleting the root O BQ UJ root M BQ U O J Textbook, p , Java Code p Inorder Successor Inorder Predecessor