DA - 3.1 - Binary Search Tree: Terminology
DA - 3.1 - Binary Search Tree: Terminology
Theory
A binary search tree is a tree where each node has a left and right child. Either child, or
both children, may be missing. The below figure illustrates a binary search tree. Assuming k
represents the value of a given node, and then a binary search tree also has the following
property: all children to the left of the node have values smaller than k, and all children to
the right of the node have values larger than k. The top of a tree is known as the root, and
the exposed nodes at the bottom are known as leaves. In Figure 3-2, the root is node 20 and
the leaves are nodes 4, 16, 37, and 43.
The height of a tree is the length of the longest path from root to leaf. For this example the
tree height is 2.
20
7
4
38
16
37
43
Assuming we replace a node by its successor, the resulting tree is shown in Figure 3-5. The
rationale for this choice is as follows. The successor for node 20 must be chosen such that
all nodes to the right are larger. Therefore we need to select the smallest valued node to the
right of node 20. To make the selection, chain once to the right (node 38), and then chain to
the left until the last node is found (node 37). This is the successor for node 20.
20
37
7
38
16
37
7
43
38
16
43
18
18
Binary Tree
after deleting Node 20
Unbalanced binary search trees are not desirable because search time increases.
Worst case running time is O(N)
o What happens when you Insert elements in ascending order?
Insert: 2, 4, 6, 8, 10, 12 into an empty BST
o Problem: Lack of balance:
compare depths of left and right subtree
o Unbalanced degenerate tree
So, best case running time of BST operations is O(log N)
Traversal:
We can traverse binary search tree in three different ways. They are
Preorder traversal
o Visit Root node, Left Node and Right node
o If traverse the above binary search tree by using preorder, you will get this
sequence F, B, A, D, C, E, G, I, H (root, left, right).
Inorder traversal:
o Visit Left Node, Root Node and Right Node
o A, B, C, D, E, F, G, H, I (left, root, right); note how this produces a sorted
sequence
Postorder traversal:
o Visit left node, right node and root
o A, C, E, D, B, H, I, G, F (left, right, root)
Example2:
Web links:
http://en.wikipedia.org/wiki/Binary_search_tree
http://www.personal.kent.edu/~rmuhamma/Algorithms/MyAlgorithms/binarySearchTree.
htm
Problem Set:
1. Write a program to traverse above example2 using Inorder, preorder and Postorder.