0% found this document useful (0 votes)
29 views

Data Structures Lab 8 9 Binary Trees

ghghg

Uploaded by

doravivek6
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views

Data Structures Lab 8 9 Binary Trees

ghghg

Uploaded by

doravivek6
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 39

Data Structures Lab 8 & 9

BINARY TREES
Outline
• Binary tree Introduction.
• Types of Binary tree.
• Representation of Binary tree using arrays and
linked list.
• Operations of Binary tree pseudocode.
• Applications of Binary tree.
• Exercise.
• Prelab Questions.
Introduction - Binary Tree
• We can represent any tree as a binary tree. Binary trees are an important type of tree
structure that occurs very often.
• In a normal tree, every node can have any number of children. Binary tree is a special
type of tree data structure in which every node can have a maximum of 2 children. One
is known as left child and the other is known as right child.
• A tree is called Binary Tree if each node has zero, one or two children,
• Empty tree is also a valid binary tree.
• We can visualize a binary tree as consisting of root, and two disjoint binary trees, called
the left and right sub-tree of the root.
• A Binary tree is a tree whose root has at most 2 children, each of which is a binary tree
Types of Binary Trees
• Strict Binary Tree: each node has exactly two children or no children.

• Full Binary Tree: each node has exactly two children or no children, and all leaf nodes are
at same level. (Also called as proper binary tree)

• Complete Binary Tree: if all leaf nodes are at level ‘h’ or ‘h-1’ and also all nodes are as far
left as possible
Properties of Binary Trees
Let us assume that the height of the tree is h.
1.Number of nodes in a FULL BINARY tree is : 2h+1-1
Since, there are h levels we need to add all nodes at
each level: [20 + 21+ 22 + ··· + 2h = 2h+1 – 1].

2.Height of FULL Binary tree with n nodes is : log2(n+1)-1

3.Number of leaf nodes in a FULL Binary tree is : 2h

4.No. of nodes a FULL Binary tree with L leaves is: 2L-1

• Number of node in a complete binary tree is between : 2h (min) and 2h+1-1(max)


• Number of NULL links (waste pointers) in a complete binary tree of n nodes is n+1.
Skewed Binary Trees
If every node in a tree has only one child(except the leaf) it is called as a skewed Tree.
Representing Binary Trees : Array(Sequential) Representation
• A single array can be used to represent a binary tree.
• If the root is stored at index 0, then
– If a node is stored at index : i
– The left child of the node is at index : 2i+1
– The right child of the node is at index : 2i+2

• If the root is stored at index 1, then


– If a node is stored at index : i
– The left child of the node is at index : 2i
– The right child of the node is at index : 2i+1

• Disadvantages :
– Wastage of space
– insertion/deletion problem
Representing Binary Trees : Linked Representation
• For simplicity, assume that the data of the nodes are integers.
• One way to represent a node (which contains data) is to have two links which point to left and right
children along with data fields as shown below:

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

left_child right_child
Operations on Binary Trees
• Basic Operations:
– Inserting an element into the tree
– Deleting an element from the tree
– Searching for an element
– Traversing the Tree (algorithm for visiting every node in a tree)
• Level Order Traversal ( Breadth-First Traversal) : Starting from the root node, visit both of
its children first, then all of its grandchildren, then great-grandchildren, until all the levels
are covered
• PreOrder : Root – Left – Right (Depth-first traversal)
• InOrder : Left – Root – Right
• PostOrder : Left – Right – Root
• Auxiliary Operations:
– Finding the size of a node/tree
– Finding the height/depth of the tree
– Finding height/depth of a node
– Finding minimum/maximum element in a binary tree
– Finding the level which has maximum sum
– Finding the parent/child of a given node
– Finding ancestors/descendants of a given node
– Finding the least common ancestor (LCA) for a given pair of nodes
Level Order Traversal – Uses Queue
• Algorithm
– Visit the root
– While traversing level l, keep all the elements at level l+1 in queue
– Go to the next level and visit all nodes at that level
– Repeat this until all levels are completed.

– Level order traversal of above tree : 1 2 3 4 5


Level Order Traversal
PseudoCode:

void LevelOrder(struct BinaryNode *root)


{
struct BinaryNode *temp;
struct Queue *Q= CreateQueue();
if(!root)
return;
EnQueue(Q,root);
while( !isEmpty(Q))
{
temp =DeQueue(Q);
printf("%d ",temp->data);
if(temp->left)
EnQueue(Q,temp->left);
if(temp->right)
EnQueue(Q,temp->right);
}
DeleteQueue(Q);
}
PreOrder Traversal – Recursive(Stack)
Algorithm
– Visit the root
– Traverse the left subtree in PreOrder
– Traverse the right subtree in PreOrder
– PreOrder traversal of above tree : 1 2 4 5 3

PseudoCode:

void PreOrder(struct BinaryNode *root)


{
if(root)
{
printf("%d ",root->data);
PreOrder(root->left);
PreOrder(root->right);
}
}
InOrder Traversal – Recursive(Stack)
Algorithm
– Traverse the left subtree in InOrder
– Visit the root
– Traverse the right subtree in InOrder
– InOrder traversal of above tree : 4 2 5 1 3

PseudoCode:

void InOrder(struct BinaryNode *root)


{
if(root)
{
InOrder(root->left);
printf("%d ",root->data);
InOrder(root->right);
}
}
PostOrder Traversal – Recursive(Stack)
Algorithm
– Traverse the left subtree in PostOrder
– Traverse the right subtree in PostOrder
– Visit the root
– PostOrder traversal of above tree : 4 5 2 3 1

PseudoCode:

void PostOrder(struct BinaryNode *root)


{
if(root)
{
PostOrder(root->left);
PostOrder(root->right);
printf("%d ",root->data);
}
}
• Non-Recursive Preorder Traversal
• Non-Recursive Inorder Traversal
• Non-Recursive Postorder Traversal
Search Operation : Binary Tree

• Given a Binary Tree, return true if a node with the given data is found in the tree.
Algorithm
– Start with the root node.
– Recurse down the tree,
– Choose the left or right branch by comparing data with each node’s data.

PseudoCode: With Recursion


int SearchKey(struct BinaryNode* root, int key)
{
int temp;
if(!root)
return 0;
else
{
if(data==root->data)
return 1;
else
{
temp = SearchKey(root->left, key);
if(temp!=0)
return temp;
else
return SearchKey(root->left, key);
}
}
return 0;
}
Search Operation : Binary Tree

PseudoCode: Using Level Order traversal


int SearchKey(struct node* root, int key)
{
struct Queue* que = createQueue(SIZE);
Enqueue(root, que);
while (!isEmpty(que))
{
struct node* temp = Dequeue(que);
if( temp->data == key)
{
return 1;
}
if (temp->left)
Enqueue(temp->left, que);

if (temp->right)
Enqueue(temp->right, que);
}
return 0;
}
Insert Operation : Binary Tree
• Given a Binary Tree, we can insert the element wherever we want. To insert an
element, we can use level order traversal and insert the element wherever we
find the node whose left child or right child is NULL.

• Algorithm
– If the tree is empty, initialize the root with new node
– Else, Push root into Queue
– Get the front node of the queue
• If the left child of this front node doesn’t exist, set the new node as the
left child
• Else if the right child of this front node doesn’t exist, set the new node
as the right child
– If the front node has both left child and right child, Dequeue it
– Enqueue the new node.
Insert Operation : Binary Tree
PseudoCode:
void insert(struct BinaryNode *root, int data)
{
struct Queue *Q;
struct BinaryNode *temp;
struct BinaryNode *newNode = (struct BinaryNode*) malloc(sizeof(struct BinaryNode));
newNode->data = data;
newNode->left = newNode->right = NULL;
if (!root)
{
root = newNode;
return;
}
Q=CreateQueue();
EnQueue(Q,root);
while(!IsEmptyQueue(Q))
{
temp = DeQueue(Q);
if (temp->left)
EnQueue(Q,temp->left);
else
{
temp->left=newNode;
DeleteQueue(Q);
return;
}
if (temp->right)
EnQueue(Q,temp->right);
else
{
temp->right=newNode;
DeleteQueue(Q);
return;
}
}
DeleteQueue(Q);
}
Delete Operation : Binary Tree
• Binary Tree Shrinks from the bottom
• Algorithm
– Starting at root, find the node which we want to delete
– Find the deepest, right most node in the tree.
– Replace the deepest right most node’s data with node to be deleted.
– Then delete the deepest rightmost node.
Delete Operation : Binary Tree
PseudoCode:
//Deleted node is replaced by deepest node - bottom most and rightmost node
struct node* delete(struct node* root, int key)
{
struct Queue* que = createQueue(SIZE);
struct node *del, *last, *temp;
Enqueue(root, que);

while (!isEmpty(que))
{
temp = Dequeue(que);
if( temp->data == key)
del= temp;
if (temp->left)
Enqueue(temp->left, que);
if (temp->right)
Enqueue(temp->right, que);
}
if (del == temp) // if the node to be deleted is the deepest node
root=del_node(root, temp);
else // if the node to be deleted is not the deepest node
{
del->data=temp->data; //copy data of the deepest node into the node whose key has to be deleted
root=del_node(root, temp);
}
return root;
}
Delete Operation : Binary Tree
PseudoCode- continuation:
struct node* del_node(struct node* root, struct node* del_node) {
struct Queue* que = createQueue(SIZE);
Enqueue(root, que);
while (!isEmpty(que)) {
struct node* temp = Dequeue(que);
if (temp==del_node){ //deleting the last remaining node of the tree
root=NULL; free(temp); return NULL;
}
if (temp->right){
if(temp->right == del_node){
temp->right=NULL; free(del_node); return root;
}
else
Enqueue(temp->right, que);
}
if (temp->left){
if(temp->left == del_node) {
temp->left=NULL; free(del_node); return root;
}
else
Enqueue(temp->left, que);
}
}
}
Binary Tree Construction

• Can you construct the binary tree,


given two traversal sequences?
• Depends on which two sequences are
given.
Preorder And Postorder

preorder = ab a a
postorder = ba b b

• Preorder and postorder do not uniquely define a


binary tree.
• Nor do preorder and level order (same example).
• Nor do postorder and level order (same
example).
Inorder And Preorder
• inorder = g d h b e i a f j c
• preorder = a b d g h e i c f j
• Scan the preorder left to right using the
inorder to separate left and right subtrees.
• a is the root of the tree; gdhbei are in the
left subtree; fjc are in the right subtree.

gdhbei fjc
Inorder And Preorder
a

gdhbei fjc
• preorder = a b d g h e i c f j
• b is the next root; gdh are in the left
subtree; ei are in the right subtree.
a

b fjc
gdh ei
Inorder And Preorder
a

b fjc
gdh ei
• preorder = a b d g h e i c f j
• d is the next root; g is in the left
subtree; h is in the right subtree.
a
b fjc
d ei
g h
Inorder And Postorder

• Scan postorder from right to left using


inorder to separate left and right subtrees.
• inorder = g d h b e i a f j c
• postorder = g h d i e b j f c a
• Tree root is a; gdhbei are in left subtree; fjc
are in right subtree.
Inorder And Level Order

• Scan level order from left to right using


inorder to separate left and right subtrees.
• inorder = g d h b e i a f j c
• level order = a b c d e f g h i j
• Tree root is a; gdhbei are in left subtree; fjc
are in right subtree.
Applications of Binary Trees

• Expression trees are used in compilers.


• Huffman coding trees that are used in data compression algorithms.
• Binary Search Tree (BST), which supports search, insertion and deletion on a
collection of items
• Priority Queue (PQ), which supports insert, search and deletion of
minimum/maximum in a collection of items .
– In this kind of queue, the element to be deleted is the one with highest( or lowest priority).
– At any time, an element with Arbitrary priority can be inserted into the queue.
– For example and MaxPiorityQueue ADT
• refer to page number 223-224 of Fundamentals of Data Structures in C, Ellis Horowitz and Sartaj Sahni, 2 nd Edition
– Applications: machine service
-amount of time (min heap)
-amount of payment (max heap)
Exercise
• Implementation of Operations on Binary Tree using Linked List.
– A) Insert
– B) Delete a node from Binary tree
– C) Delete entire Binary tree
– D) Preorder
– E) Inorder
– F) Postorder
– G) Level Order
– H) Search a node value
– I) Count number of nodes in Binary tree
– J) Display height of a Binary tree
– K) Display sum of nodes of a Binary tree
• Implement the above one with the help of array.
• Implementation of Recursive Traversals on Binary Trees.
– Preorder
– Postorder
– Inorder
• Implementation of Iterative Traversals on Binary Trees.
– Preorder
– Postorder
– Inorder
Prelab Questions
• Give the procedure to print left view of a Binary tree
• Give the procedure to determine if given two nodes are cousins
of each other
• Give procedure to print all paths from root to leaf nodes in a
binary tree.
• Procedure to build binary tree from its traversals.
(Inorder,Preorder,Postorder).

In the following link questions look interesting, all the students try
to learn all and code by yourself.
https://medium.com/techie-delight/binary-tree-interview-
questions-and-practice-problems-439df7e5ea1f

You might also like