Binary Search Trees
Binary Search Trees
Key
Key Left
Left Right
Right
Key
Key Left Right
Key
Left Right
8
4
6
2
1
8
4
a) 22 > 17
b) 11 < 17
c) 11 > 6
d) 22 > 17
The search tree property does not say what happens with
the elements with the same key. In our examples, all the
keys will be distinct but in practice it is important to cover
the case of multiple elements with the same key (duplicate
keys).
The duplicate keys can all be kept in the left subtree, or all
in the right subtree. It doesnt matter which we choose, but
it matters that the choice is the same for the whole
implementation.
Another issue: with duplicate keys, it is important to have
extra operations in the interface: getAll, and removeAll
Insertion
Search
Traversal
Deletion
Find Minimum
Find the item that has the minimum value in the tree
Find Maximum
Successor
Predecessor
t
2
NULL
NULL
NULL
NULL
t
1
NULL
NULL
NULL
NULL
NULL
New Node
InOrder_Tree_Walk(x)
{
if x NULL
InOrder_Tree_Walk(left[x])
print key[x]
InOrder_Tree_Walk(right[x])
}
BST-inorder-traverse (node)
1. If node has left child
BST-inorder-traverse (Left(node))
2. Apply operation to node (e.g. cout)
3. If node has right child
BST-inorder-traverse (Right(node))
Order for tree above: 1, 2, 3, 5, 6, 7
Application: Display tree in ascending
order
BST-preorder-traverse (node)
1. Apply operation to node e.g cout
2. If node has left child
BST-preorder-traverse (Left(node))
3. If node has right child
BST-preorder-traverse (Right(node))
BST-postorder-traverse (node)
1. If node has left child
BST-postorder-traverse (Left(node))
2. If node has right child
BST-postorder-traverse (Right(node))
3. Apply operation to node e.g cout
Order for tree above: 2, 1, 5, 7, 6, 3
Application: Deallocate BST
Were done
When given a pointer to the root of a tree and a key, TreeSearch will return a pointer to the node with key k if one exists
(x = root).
Tree-Search (x, k)
{
if x=NULL or k=key[ x]
return x
if k<key [x]
return Tree-Search( left[ x], k)
else
return Tree-Search( right[ x], k)
}
8
4
15
5
20
18
25
45
40
15
removeElement(45)
------------->
20
18
15
5
20
45
18
removeElement(20)
------------->
5
25
40
15
18
45
15
5
20
45
25
40
18
18
removeElement(15)
------------->
20
18
45
6
2
1
8
5
8
5
3
4
before
Deletion of node 2.
4
after