Binary Search Tree Neil Tang 01/31/2008 CS223 Advanced Data Structures and Algorithms
CS223 Advanced Data Structures and Algorithms Class Overview Definition Operations: contains, findMin, findMax, insert, remove Time complexity analysis CS223 Advanced Data Structures and Algorithms
CS223 Advanced Data Structures and Algorithms Definition A Binary Search Tree is a special binary tree in which for each node X, the values of all the items in its left subtree are smaller than that in X and the values of all the items in its right subtree are larger than that in X. CS223 Advanced Data Structures and Algorithms
CS223 Advanced Data Structures and Algorithms Operations contains: find out if a binary search tree contains a given item x. CS223 Advanced Data Structures and Algorithms
CS223 Advanced Data Structures and Algorithms Operations findMin/findMax: find the smallest/largest item in a binary search tree. CS223 Advanced Data Structures and Algorithms
CS223 Advanced Data Structures and Algorithms Operations insert: insert an item into a binary search tree. 14 2 9 5 12 18 19 17 13 15 2 9 5 12 18 19 17 14 15 13 2 9 5 12 18 19 17 14 15 13 14 14 2 9 5 12 18 19 17 13 15 2 9 5 12 18 19 17 13 15 CS223 Advanced Data Structures and Algorithms
CS223 Advanced Data Structures and Algorithms Operations CS223 Advanced Data Structures and Algorithms
CS223 Advanced Data Structures and Algorithms Operations remove: delete an item in a binary search tree. 15 15 5 3 10 6 7 23 16 18 20 12 5 16 Case 1: 3 12 20 18 23 10 13 6 7 15 5 3 10 6 7 23 16 18 20 13 12 15 5 3 10 6 7 23 18 20 13 12 Case 2: 15 5 3 10 6 7 23 16 18 20 13 12 15 5 3 6 23 16 18 20 13 12 10 7 Case 3: CS223 Advanced Data Structures and Algorithms
CS223 Advanced Data Structures and Algorithms Operations CS223 Advanced Data Structures and Algorithms
Time Complexity Analysis The time complexities of almost all operations on a binary search tree are O(d), where d is the depth (height) of the tree. d = 3 = log(N+1)-1 = O(logN) d = 7 = (N+1)/2 - 1 = O(N) d = N-1 = O(N) Theorem: The average height of a randomly built (insertion) binary search tree on N keys is (logN) . (pp.268 Cormen’s book) CS223 Advanced Data Structures and Algorithms