6-Binary Search Trees
6-Binary Search Trees
Fall 2005
Binary Trees,
Binary Search Trees
Trees
Linear access time of linked lists is prohibitive
Does there exist any simple data structure for which the running time
of most operations (search, insert, delete) is O(log N)?
Trees
A tree is a collection of nodes
The collection can be empty
(recursive definition) If not empty, a tree consists of a distinguished
node r (the root), and zero or more nonempty subtrees T1, T2, ...., Tk,
each of whose roots are connected by a directed edge from r
Some Terminologies
Inorder traversal
left, node, right.
infix expression
a+b*c+d*e+f*g
Preorder
Postorder
Preorder, Postorder and Inorder
Binary Trees
Possible operations on the Binary Tree ADT
parent
left_child, right_child
sibling
root, etc
Implementation
Because a binary tree has at most two children, we can keep
direct pointers to them
compare: Implementation of a general tree
Binary Search Trees
Stores keys in the nodes in a way so that searching,
insertion and deletion can be done efficiently.
Binary search tree property
For every node X, all the keys in its left subtree are smaller than
the key value in X, and all the keys in its right subtree are larger
than the key value in X
Binary Search Trees
Time complexity
O(height of the tree)
Inorder traversal of BST
Print out all the keys in sorted order