chapter 9 contd. binary search trees
DESCRIPTION
Chapter 9 contd. Binary Search Trees. Anshuman Razdan Div of Computing Studies [email protected] http://dcst2.east.asu.edu/~razdan/cst230/. BST and Total Order. Binary search trees are a subset (generalization) of Binary Trees - PowerPoint PPT PresentationTRANSCRIPT
Chapter 9 contd.Binary Search Trees
Anshuman RazdanDiv of Computing Studies
[email protected]://dcst2.east.asu.edu/~razdan/cst230/
CST 230 Razdan et al 2
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 3
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 4
Example
45
9 53
3 17
20
53 54
CST 230 Razdan et al 5
Typical BST Methods
• add
• remove
• find
• other variations:– find min– find max– add/combine BSTs
CST 230 Razdan et al 6
add a new Node
• Suppose we want to add 23 and 50 to the following BST
45
9 53
3 17
20
53 54
CST 230 Razdan et al 7
add cont...if tree is empty
make the new node the rootelse insert in the subtree under the current root
if val <= rootif root has left child
insert in subtree under left childelse
make val the left childelse
if root has right childinsert in subtree under right child
elsemake val the right child
CST 230 Razdan et al 8
remove
• Suppose we want to remove 17, 45 from the BST
45
9 53
3 17
20
53 54
CST 230 Razdan et al 9
remove cont...
find node to removeif node is a leaf
set parent’s appropriate child to nullelse if node has no left child
set parent’s appropriate child to right childelse if node has no right child
set parent’s appropriate child to left childelse
set data in node to max value in left subtreeremove max value in left subtree
CST 230 Razdan et al 10
Complexity of BST methods
• Best Case– find
– add
– remove
• Worst Case– find
– add
– remove