Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 Lecture 21: Binary Search Tree delete etc. operations Lecturer: Santokh Singh CompSci 105 SS 2005 Principles of Computer Science.

Similar presentations


Presentation on theme: "1 Lecture 21: Binary Search Tree delete etc. operations Lecturer: Santokh Singh CompSci 105 SS 2005 Principles of Computer Science."— Presentation transcript:

1 1 Lecture 21: Binary Search Tree delete etc. operations Lecturer: Santokh Singh CompSci 105 SS 2005 Principles of Computer Science

2 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. 423-4 >K <K

3 3 Searching M BQ JUO

4 4 Add as a leaf M BQ JUO

5 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 4 3 2 7 5 6

6 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 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 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 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 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 11 BST Delete M BQ JUO

12 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. 461-462

13 13 BST Delete M BQ JUO

14 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 15 Deleting the root BQ U O J root M BQ U O J Textbook, p. 463-4, Java Code p. 466-469

16 16 Deleting the root BQ U O J root M BQ U O J Textbook, p. 463-4, Java Code p. 466-469

17 17 Deleting the root O BQ UJ root M BQ U O J Textbook, p. 463-4, Java Code p. 466-469 Inorder Successor Inorder Predecessor


Download ppt "1 Lecture 21: Binary Search Tree delete etc. operations Lecturer: Santokh Singh CompSci 105 SS 2005 Principles of Computer Science."

Similar presentations


Ads by Google