You are on page 1of 42

CSEE2123: OOP and Data Structures

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

–Finalterm Percentage 40%


–Finalterm will be Comprehensive

1/8/2019 CSEE1133:Data Structures © M. Tahir Awan, CUST 2


Assignment # 4 :
Programming Assignment
• Due Date :
– Thursday, January 10th , 2019
– Due at : 05:00 p.m.
• Late Submission
– Not Allowed
• Assignment Submission
– Separate *.cpp file for each Question
– Submit in zip format
– File name : “Name_RollNo_AssignNo.zip”
– Submission Path
» \\fs\assignments$\mTahir\OOP\Assignment4

1/8/2019 CSE2132:Computer Programming © M. Tahir Awan, CUST 3


Advanced Data Structures
• Linear Data Structures
–Arrays
–Linked Lists
–Stacks
–Queues
• Non-Linear Data Structures
–Trees
–Binary Trees

1/8/2019 CSEE1133:Data Structures © M. Tahir Awan, CUST 4


Trees : Non-Linear Data Structure
• A tree is a non-linear data structure, that is
composed of multiple nodes connected through
edges
• Each node in a tree may have one or more child
nodes and are organized in a hierarchical
fashion

1/8/2019 CSEE1133:Data Structures © M. Tahir Awan, CUST 5


Binary Tree
• Binary Tree is a special tree where each parent
node has at maximum two child nodes
• Tree starts at the root node i.e. node at the top
• Leaf node in the tree does not have any child
nodes
root
• Root Node 1 has two
child nodes (Left Node
:2 , Right Node:3) 1
• Nodes are connected
through edges 2 3
• Each tree has one root
node 4 5 6 7
1/8/2019 CSEE1133:Data Structures © M. Tahir Awan, CUST 6
Binary Tree : Definitions
• Path :
• Path refers to the sequence of nodes from Node
X to node Y
• Level :
• Level of a node in a binary tree is the number of
edges on the path from the root to that node
• Height :
• Height of a binary tree is the number of nodes on
the longest path from the root to a leaf node
• Subtree:
• the smaller tree of nodes on the left or right of
the current node
1/8/2019 CSEE1133:Data Structures © M. Tahir Awan, CUST 7
Binary Tree
• Nodes D, H, I form a sub-tree on Left of Node B
• Node B is at Level 1, Node F at Level 2
• Total Nodes = 10 ,
• Leaf nodes = 5,
• Height = 4

1/8/2019 CSEE1133:Data Structures © M. Tahir Awan, CUST 8


Binary Tree : Implementation
• Binary tree can be dynamically implemented as
sequence of nodes
• Each node contain one data field and left & right
node pointers

struct tree_node
{
int data;
tree_node* left;
tree_node* right;
};

1/8/2019 CSEE1133:Data Structures © M. Tahir Awan, CUST 9


Binary Tree: Operations
• Following operations can be performed on the
Binary Tree
– Initialize & build the tree
– Find Height of the tree
– Count Total Nodes & Leaf Nodes
– Traverse the Binary Tree
– Check if Tree is empty
– Add and item in the Tree
– Remove an item from the Tree
– Search an item in the Tree
– Make a copy of the Tree
– Display
1/8/2019
all nodes in the Tree
CSEE1133:Data Structures © M. Tahir Awan, CUST 10
Binary Tree Implementation : Class
• A C++ Class to struct tree_node {
tree_node* left;
implement Binary tree_node* right;
Tree int data;
};
• Tree Attributes class BinaryTree {

• Tree Operations private:


tree_node* root;
public:

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 {

• Tree will be empty (No };


root = NULL;

Nodes) if root is NULL


bool BinaryTree :: IsEmpty()
{
return root == NULL
}

1/8/2019 CSEE1133:Data Structures © M. Tahir Awan, CUST 12


Binary Tree : Finding Height
• If the binary tree is empty, height is 0
• To find the height of non-empty tree, find height
of left sub-tree and right sub-trees of root node,
take the maximum and add one to it
• To find the height of sub-
tree , recursively apply the
same approach
• Height = 1 + max (Height
of Left Sub-Tree, Height of
Right Sub-Tree )

1/8/2019 CSEE1133:Data Structures © M. Tahir Awan, CUST 13


Binary Tree : Finding Height
• To find the height of int BinaryTree::findHeight(tree_node* p)
{
sub-tree , recursively if (p == NULL){
apply the findHeight return 0;
function at each sub }
else {
tree int h1 = findHeight(p->left);
• Height = 1 + max int h2 = findHeight(p->right);
int max = h1 > h2 ? h1 : h2;
(Height of Left Sub- return 1 + max;
Tree, Height of Right }
Sub-Tree ) }

1/8/2019 CSEE1133:Data Structures © M. Tahir Awan, CUST 14


Binary Tree : Traversal
• Traversal is the process to visit all the nodes of a
binary tree. Traversal starts from the root node
• Tree traversal is used in insertion, deletion &
searching operations on trees
• There are three methods to traverse a binary tree
Root
–In-order Traversal
–Pre-order Traversal 17
–Post-order Traversal
41 9

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}

1/8/2019 CSEE1133:Data Structures © M. Tahir Awan, CUST 16


Pre-order Traversal
• In a pre-order traversal, the binary tree is traversed
as follows:
– Visit the node
– Traverse the left subtree
– Traverse the right subtree
– Repeat recursively

• Pre-order Sequence =
• {A, B, D, E, C, F, G}

1/8/2019 CSEE1133:Data Structures © M. Tahir Awan, CUST 17


Post-order Traversal
• In a post-order traversal, the binary tree is
traversed as follows:
– Traverse the left subtree
– Traverse the right subtree
– Visit the node
– Repeat recursively

• Post-order Sequence =
• {D, E, B, F, G, C, A}

1/8/2019 CSEE1133:Data Structures © M. Tahir Awan, CUST 18


Traversal trick
• To quickly generate a traversal Root
Sequence:
– Trace a path around the tree. 17
– As you pass a node on the
proper side, process it. 41 9
• in-order: bottom
• pre-order: left side 29 6 81 40
• post-order: right side

• In-order Sequence: {29 41 6 17 81 9 40}


• Pre-order Sequence: {17 41 29 6 9 81 40}
• Post-order Sequence: {29 6 41 81 40 9 17}
1/8/2019 CSEE1133:Data Structures © M. Tahir Awan, CUST 19
Binary Tree Traversal :
Practice Question
• Find In-order, pre-order Root
and post-order traversal
sequences for binary tree 42
shown
15 9

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

• Breadth First Traversal: {17 41 9 29 6 81 40}

1/8/2019 CSEE1133:Data Structures © M. Tahir Awan, CUST 21


Binary Tree Implementation : Class
• A C++ Class to struct tree_node {
tree_node* left;
implement Binary tree_node* right;
Tree int data;
};
• Tree Attributes class BinaryTree {

• Tree Operations private:


tree_node* root;
public:

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.

int BinaryTree:: inOrder(tree_node* p)


{
if (p != NULL)
{
inOrder(p->left);
cout << p->data << " ";
inOrder(p->right);
}
}

1/8/2019 CSEE1133:Data Structures © M. Tahir Awan, CUST 23


Pre-order Traversal : Implementation
• Algorithm for pre- • Until all nodes are traversed
order tree traversal • Visit root node
• Recursively traverse left
subtree
• Recursively traverse right
subtree

int BinaryTree:: preOrder(tree_node* p)


{
if (p != NULL)
{
cout << p->data << " ";
preOrder(p->left);
preOrder(p->right);
}
}

1/8/2019 CSEE1133:Data Structures © M. Tahir Awan, CUST 24


Post-order Traversal : Implementation
• Algorithm for post- • Until all nodes are traversed
order tree traversal • Recursively traverse left
subtree
• Recursively traverse right
subtree
• Visit root node

int BinaryTree:: postOrder(tree_node* p)


{
if (p != NULL)
{
postOrder(p->left);
postOrder(p->right);
cout << p->data << " ";
}
}

1/8/2019 CSEE1133:Data Structures © M. Tahir Awan, CUST 25


Binary Tree : Count Total, Leaf Nodes
• Functions to count int
{
BinaryTree::CountTotalNodes()

total nodes of the tree . . .


and Leaf nodes of the . . .
tree . . .
}
• Complete the
Functions
int BinaryTree::CountLeafNodes()
{
. . .
. . .
. . .
}

1/8/2019 CSEE1133:Data Structures © M. Tahir Awan, CUST 26


Binary Tree : Searching
• Search 53 in the binary
tree ?
• In order to search a value
in binary tree we need to
traverse the whole tree in
some order (inorder,
preorder, postorder)

• Binary Search Tree can be


used to speed up search

1/8/2019 CSEE1133:Data Structures © M. Tahir Awan, CUST 27


Binary Search Tree (BST)
• Binary Search trees are binary trees that exhibit
a special behavior.
– Value of the root node is larger than all the
nodes in left sub-tree
– Value of the root node is smaller than all the
nodes in right sub-tree

1/8/2019 CSEE1133:Data Structures © M. Tahir Awan, CUST 28


Binary Search Tree Implementation :
Class
• A C++ Class to struct tree_node {
tree_node* left;
implement Binary tree_node* right;
Search Tree int data;
};
• Tree Attributes class BinarySearchTree {

• Tree Operations private:


tree_node* root;
public:

BinarySearchTree();
bool isEmpty();
void insertItem(int);
void removeItem(int);
bool searchItem(int);
int findHeight();
int countTotalNodes();
int countLeafNodes();
};

1/8/2019 CSEE1133:Data Structures © M. Tahir Awan, CUST 29


Binary Search Tree : Searching
• Algorithm for searching in a
binary search tree
– Compare the data to be
searched with root node ,
if found we are done
– If data to be searched is
less than root node ,
search in the left sub-
tree
– If data to be searched is
greater than root node,
search in the right sub-
tree
1/8/2019 CSEE1133:Data Structures © M. Tahir Awan, CUST 30
Binary Search Tree : Searching
• Functions to search int BinarySearchTree:: searchItem(int
value) {
data in a binary tree_node *current;
search tree bool found = false;
if (root == NULL)
cout << "Empty tree." << endl;
else {
current = root;
while (current != NULL && !found){
if (current->data == value)
found = true;
else if (current->data > value)
current = current->left;
else
current = current->right;
}
}
return found;
}

1/8/2019 CSEE1133:Data Structures © M. Tahir Awan, CUST 31


Traversal in Binary Search Trees
• Three Traversal Methods Root
• in-order
• pre-order 25
• post-order
• In order traversal in binary 15 45
search trees generates a sorted
sequence (ascending order)
9 21 33 77

• In-order Sequence: {9 15 21 25 33 45 77}


• Pre-order Sequence: {25 15 9 21 45 33 77}
• Post-order Sequence: {9 21 15 33 77 45 25}
1/8/2019 CSEE1133:Data Structures © M. Tahir Awan, CUST 32
Binary Search Tree : Insert Item
• In order to insert data in a
binary search tree, first find
the position, where data
should be inserted using
search algorithm
• New item inserted will
always be a leaf node
• Tree should be binary
search tree before and after
insertion of new item
• Binary search tree does not
contain duplicate data

1/8/2019 CSEE1133:Data Structures © M. Tahir Awan, CUST 33


Binary Search Tree :
Practice Question
• Draw a binary search tree, if nodes are inserted
in the order
• 35, 66, 12, 25, 44, 51, 19, 9, 81

CSEE2123:OOP & Data Structures © M. Tahir Awan, CUST 34


Binary Search Tree : Insert Item
• Functions to insert int BinarySearchTree:: insertItem(int
value) {
data in a binary tree_node *current;
search tree tree_node *parent;
tree_node *newNode;

newNode = new tree_node;


newNode->data = value;
newNode->left = NULL;
newNode->right = NULL;

if (root == NULL)
root = newNode;
else {
current = root;
while (current != NULL) {
parent = current;

//contd...

1/8/2019 CSEE1133:Data Structures © M. Tahir Awan, CUST 35


Binary Search Tree : Insert Item
• Functions to insert if (current->data == value){
cout << "Duplicates“ <<endl;
data in a binary return;
search tree }
else if (current->data > value)
current = current->left;
else
current = current->right;
}

if (parent->data > value)


parent->left = newNode;
else
parent->right = newNode;
}

1/8/2019 CSEE1133:Data Structures © M. Tahir Awan, CUST 36


Binary Search Tree : Remove Item
• In order to remove data
from a binary search tree,
first locate the node
• 4 Cases :
• Case 1: Node to be removed
is a leaf node
• Case 2: Node to be removed
has only left child
• Case 3: Node to be removed
has only right child
• Case 4: Node to be removed
has both left and right
Childs
1/8/2019 CSEE1133:Data Structures © M. Tahir Awan, CUST 37
Binary Search Tree : Remove Item
• Case 1 : Remove Leaf Node : 45
Before After

1/8/2019 CSEE1133:Data Structures © M. Tahir Awan, CUST 38


Binary Search Tree : Remove Item
• Case 2 : Remove Node with right child only : 30
Before After

1/8/2019 CSEE1133:Data Structures © M. Tahir Awan, CUST 39


Binary Search Tree : Remove Item
• Case 3 : Remove Node with left child only : 80
Before After

1/8/2019 CSEE1133:Data Structures © M. Tahir Awan, CUST 40


Binary Search Tree : Remove Item
• Case 4 : Remove Node with both Childs : 50
Before After

1/8/2019 CSEE1133:Data Structures © M. Tahir Awan, CUST 41


Binary Search Tree : Remove Item
• Case 4 : Remove Node with both Childs : 50

• 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

1/8/2019 CSEE1133:Data Structures © M. Tahir Awan, CUST 42

You might also like