Binary Search Tree
Binary Search Tree
key < n
All key in
the left subtree is less
than n
20
8
key > n
All key in the right
sub-tree are
greater than n
40
15
10
18
Kamal
A pointer-based implementation of a
binary tree
Node Implementation
leftPtr
info
rightPtr
F
Node representation
Tree Implementation
class TreeType {
public:
TreeType();
~TreeType();
bool IsEmpty()const;
int NumberOfNodes()const;
void RetrieveItem(ItemType&,bool& found);
void InsertItem(ItemType);
void DeleteItem(ItemType);
void PrintTree() const;
private:
TreeNode * root;
};
Tree Operations
Among the tree operations in the class TreeType:
1. Initialize tree , using constructor.
2. Destroy tree, destructor.
3. Check for empty tree, IsEmpty().
4. Count number of nodes in the tree.
5. Search item in the tree
6. Insert item into a tree.
7. Delete item from tree.
8. Print all item in the tree (Inorder traversal)
Tree Constructor
TreeType::TreeType()
{
root = NULL;
}
Tree Destructor
TreeType::~TreeType()
{
Destroy(root);
}
void Destroy(TreeNode *& tree)
{
if (tree!=NULL)
{
Destroy(tree->left);
Destroy(tree->right);
delete(tree);
}
}
Step 2
Destroying
third node
Destroying
sixth node,
root
Destroying
fifth node
Step 3
Destroying
fourth node
IsEmpty()Function
Binary Search Tree is Empty when the root has
NULL value.
Function IsEmpty() will return True if root is NULL
and will return False if the root is not NULL.
bool IsEmpty() const
{ if (root == NULL)
return True; // tree is empty
else
return False; // tree is not empty
}
root
Jimmy
root
Jimmy
Fizzi
Liana
Jimmy
Fizzi
Liana
Hazim
Empty tree
Insert 5
Insert 10
Insert 8
Insert 3
Insert 4
Before delete
After delete Z
Before delete R
After delete R
Replace with 3
and delete
node 3
References
Nor Bahiah et al. Struktur data & algoritma
menggunakan C++. Penerbit UTM. 2005.
Frank M. Carano, Janet J Prichard. Data
Abstraction and problem solving with C++
Walls and Mirrors. 5th edition (2007). Addision
Wesley.