100 likes | 178 Views
Chapter 9 contd. Binary Search Trees. Anshuman Razdan Div of Computing Studies razdan@asu.edu http://dcst2.east.asu.edu/~razdan/cst230/. BST and Total Order. Binary search trees are a subset (generalization) of Binary Trees
E N D
Chapter 9 contd.Binary Search Trees Anshuman Razdan Div of Computing Studies razdan@asu.eduhttp://dcst2.east.asu.edu/~razdan/cst230/
BST and Total Order • Binary search trees are a subset (generalization) of Binary Trees • The set of objects stored in a binary tree must come from a totally ordered set • A Total Order has the following mathematical properties: • Equality • Totality • Consistency • Transitivity CST 230 Razdan et al
BST Definition • In a Binary Search Tree, the elements of the nodes can be compared with a total order semantics. These two rules are followed for every node n: • Every element in n’s left subtree is less than or equal to the element in n • Every element in n’s right subtree is greater than or equal to the element in n. CST 230 Razdan et al
9 53 45 20 53 54 3 17 Example CST 230 Razdan et al
Typical BST Methods • add • remove • find • other variations: • find min • find max • add/combine BSTs CST 230 Razdan et al
9 53 45 53 54 20 3 17 add a new Node • Suppose we want to add 23 and 50 to the following BST CST 230 Razdan et al
add cont... if tree is empty make the new node the root else insert in the subtree under the current root if val <= root if root has left child insert in subtree under left child else make val the left child else if root has right child insert in subtree under right child else make val the right child CST 230 Razdan et al
9 53 45 53 54 20 3 17 remove • Suppose we want to remove 17, 45 from the BST CST 230 Razdan et al
remove cont... find node to remove if node is a leaf set parent’s appropriate child to null else if node has no left child set parent’s appropriate child to right child else if node has no right child set parent’s appropriate child to left child else set data in node to max value in left subtree remove max value in left subtree CST 230 Razdan et al
Best Case find add remove Worst Case find add remove Complexity of BST methods CST 230 Razdan et al