Professional Documents
Culture Documents
Fall 2018
Binary Trees
Lecture 31
M. Tahir Awan
(mtahir@cust.edu.pk)
Capital University of Science & Technology (CUST),
Islamabad
Final-Term Exam (Tentative)
• Final-Term Date & Time
–Date : January 19, 2019 (Saturday)
–Time : 01:30 pm
struct tree_node
{
int data;
tree_node* left;
tree_node* right;
};
BinaryTree();
bool isEmpty();
int findHeight();
void inOrder(tree_node*);
void preOrder(tree_node*);
void postOrder(tree_node*);
int countTotalNodes();
int countLeafNodes();
};
1/8/2019 CSEE1133:Data Structures © M. Tahir Awan, CUST 11
Binary Tree : Creation & Initialization
• Constructor will //Constructor
BinaryTree :: BinaryTree ()
initialize root to NULL {
29 6 81 40
1/8/2019 CSEE1133:Data Structures © M. Tahir Awan, CUST 15
In-order Traversal
• In an in-order traversal, the binary tree is traversed
as follows:
– Traverse the left subtree
– Visit the node
– Traverse the right subtree
– Repeat recursively
•
• In-order Sequence =
• {D, B, E, A, F, C, G}
27 86 3
48 12 39
5
1/8/2019 CSEE1133:Data Structures © M. Tahir Awan, CUST 20
Binary Tree : Breadth First Traversal
• Traverse all the nodes at one Root
level before moving to the next
level, starting from level 0
17
41 9
29 6 81 40
BinaryTree();
bool isEmpty();
int findHeight();
void inOrder(tree_node*);
void preOrder(tree_node*);
void postOrder(tree_node*);
int countTotalNodes();
int countLeafNodes();
};
1/8/2019 CSEE1133:Data Structures © M. Tahir Awan, CUST 22
In-order Traversal : Implementation
• Algorithm for in-order • Until all nodes are traversed
tree traversal • Recursively traverse left
subtree.
• Visit root node.
• Recursively traverse right
subtree.
BinarySearchTree();
bool isEmpty();
void insertItem(int);
void removeItem(int);
bool searchItem(int);
int findHeight();
int countTotalNodes();
int countLeafNodes();
};
if (root == NULL)
root = newNode;
else {
current = root;
while (current != NULL) {
parent = current;
//contd...
• Algorithm
• Find position of the node to be removed
• Find a minimum value in the right sub-tree OR
maximum value in the left sub-tree
• Replace value of the node to be removed with
found minimum/maximum.
• To remove duplicate value, it becomes Case 2 or
Case 3 i.e node with one child. Remove the
duplicate node accordingly