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

Module 4

The document outlines the syllabus for a Data Structures course, focusing on Binary Trees and Binary Search Trees (BST), including their properties, operations, and applications. It details tree terminology, traversal methods, and provides C programming examples for creating and manipulating binary trees and heaps. Additionally, it covers the concept of expression trees and their construction using stacks.

Uploaded by

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

Module 4

The document outlines the syllabus for a Data Structures course, focusing on Binary Trees and Binary Search Trees (BST), including their properties, operations, and applications. It details tree terminology, traversal methods, and provides C programming examples for creating and manipulating binary trees and heaps. Additionally, it covers the concept of expression trees and their construction using stacks.

Uploaded by

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

DAYANANDA SAGAR COLLEGE OF ENGINEERING

(An Autonomous Institute Affiliated to VTU, Belagavi)

Course: Data Structures with Applications Course code: 21CS34


Semester: III

UNIT -4
Syllabus: Binary Trees: Binary Tree properties and representations, traversals
and other operations. Binary Search Trees: Definition, Operations on BST.
Applications of Trees: Expression Trees, Heaps.

TREES: Introduction to Binary Search Trees (BST), Properties of Binary Tree, Operation on
BST, Traversals in Binary Trees, Heaps, Selection Trees, Forests tree, Counting Binary Trees.

Tree is a nonlinear non primitive data structure. Tree is a finite set of one or more nodes such
that each node contains the address of other node. The node A is the root node.

Figure 1 Tree
Terminologies:

Root: It is the unique node in the tree to which further subtree are attached, for above given tree,
node 2 is the root node.

Degree of node: The total number of subtree connected to a node is called degree of a node. For
example degree of node K is 1, degree of node C is 2 in figure 1 and degree of node B is 3 and
degree of leaf node is always zero.

Level of a tree: The root node to be at level 0 and the children of the root node are at level 1 and
the children of the node which are at level 1 will be at level 2 and so on.

Height of a tree: The total number of edges from leaf node to a particular node in the longest
path is called height of that node. The height of a root node is said to be height of the tree. Figure
1 height of a tree is 3.

Leaf node: The node which does not have a child is called as leaf node. In figure 1 the leaf
nodes are D, I, J, F, K , H.

Internal node: The node with atleast one node is called internal node. In figure 1 the internal
nodes are A, B, C, E & G.

Depth: The total number of edges from root node to a particular node is called depth of that
node.

Binary Search Tree (BST)

A binary tree is a finite set nodes which is either empty or consists of a root and two disjoint
binary tree called left subtree and right subtree. Based on principle LST <= ROOT < RST.

Tree representation using linked list.

Complete binary tree: A binary tree T with n levels is complete if all levels except possibly the
last are completely full, and the last level has all its nodes to the left side.

Full Binary Tree Theorem

Theorem: Let T be a nonempty, full binary tree then:

1. If T has I internal nodes, the number of leaves is L = I + 1.

2. If T has I internal nodes, the total number of nodes is N = 2I + 1.


3. If T has a total of N nodes, the number of internal nodes is I = (N – 1)/2.

4. If T has a total of N nodes, the number of leaves is L = (N + 1)/2.

5. If T has L leaves, the total number of nodes is N = 2L – 1.

6. If T has L leaves, the number of internal nodes is I = L – 1.

Proof of Full Binary Tree Theorem

We will use induction on the number of internal nodes, I. Let S be the set of all integers I ³ 0 such
that if T is a full binary tree with I internal nodes then T has I + 1 leaf nodes. For the base case, if
I = 0 then the tree must consist only of a root node, having no children because the tree is full.
Hence there is 1 leaf node, and so 0 Î S.

Now suppose that for some integer K ³ 0, every I from 0 through K is in S. That is, if T is a
nonempty binary tree with I internal nodes, where 0 ≤ I ≤ K, then T has I + 1 leaf nodes. Let T be
a full binary tree with K + 1 internal nodes. Then the root of T has two subtrees L and R; suppose
L and R have IL and IR internal nodes, respectively. Note that neither L nor R can be empty, and
that every internal node in L and R must have been an internal node in T, and T had one
additional internal node (the root), and so K + 1=IL + IR + 1. Now, by the induction hypothesis,
L must have IL+1 leaves and R must have IR+1 leaves. Since every leaf in T must also be a leaf
in either L or R, T must have IL + IR + 2 leaves. Therefore, doing a tiny amount of algebra, T
must have K + 2 leaf nodes and so K + 1 Î S. Hence by Mathematical Induction, S = [0, ¥).

Example 1: Given a sequence of numbers: 11, 6, 8, 19, 4, 10, 5, 17, 43, 49, 31

Draw a binary search tree by inserting the above numbers from left to right.

Function to insert a node:

1. Read the value of the node which is to be created and store it in a node called new

2. Initially if (root==NULL) then root =new

3. Again read the next value of node created in new

4. if (new->data < root_data) then connect the new node as a left child of the root otherwise
the right child of a root.

5. Repeat step 3 and 4 for the construction of a complete binary tree.


13, 3, 4, 12, 14, 10, 5, 1, 8, 2, 7, 9, 11, 6, 18 in that order, starting from an empty tree.

NODE *CreateBST(NODE *root, int elem)

if(root == NULL)

root=(NODE *)malloc(sizeof(NODE));

root->left= root->right = NULL;

root->data=elem;

return root;

else
{

if( elem < root->data )

root->left=CreateBST(root->left,elem);

else

if( elem > root->data )

root->right=CreateBST(root->right,elem);

else

printf(" Duplicate Element !! Not Allowed !!!");

return(root);

Traversals

A traversal is a process that visits all the nodes in the tree. Since a tree is a nonlinear data
structure, there is no unique traversal.

There are three different types of traversals


● PreOrder traversal - visit the parent first and then left and right children;
● InOrder traversal - visit the left child, then the parent and the right child;
● PostOrder traversal - visit left child, then the right child and then the parent;

As an example consider the following tree and its tree traversals:

PreOrder - 8, 5, 9, 7, 1, 12, 2, 4, 11, 3


InOrder - 9, 5, 1, 7, 2, 12, 8, 4, 3, 11
PostOrder - 9, 1, 2, 12, 7, 5, 3, 11, 4, 8
Recursive inorder traversal C function

Void inorder(Node temp)


{
if (temp!=NULL)
{
inorder(temp->lptr)
printf(“%d”,temp->data);
inorder(temp->rptr)
}

Recursive postorder traversal C function

Void postorder(Node temp)


{
if (temp!=NULL)
{
postorder(temp->lptr)
postorder(temp->rptr
printf(“%d”,temp->data);

}
}

Recursive preorder traversal C function

Void preorder(Node temp)


{
if (temp!=NULL)
{
printf(“%d”,temp->data);
preorder(temp->lptr)
preorder(temp->rptr

}
}

1. Design, develop and execute a program in C to create a max heap of integers by accepting
one element at a time and by inserting it immediately in to the heap. Use the array representation
for the heap. Finally display the heap list.
#include<stdio.h>
#include<time.h>
void heapify(int [],int );
void adjust(int [],int ,int);
void hsort(int [],int );
void main()
{
int a[10], n, i;
clrscr();
printf("Enter the no of elements\n");
scanf("%d",&n);
printf("Enter the elements \n");
for(i=1;i<=n;i++)
scanf("%d",&a[i]);
heapify(a,n);
printf("The BST elements are \n");
for(i=1;i<=n;i++)
printf("%d\n",a[i]);
}

void heapify(int a[],int n)


{
int i;
for(i=n/2;i>=1;i--)
adjust(a,i,n);
}

void adjust(int a[], int i, int n)


{
int j, v, heap, k;
k=i;
v=a[k];
heap=0;
while(!heap && (2*k)<=n)
{
j=2*k;
if(j<n)
{
if(a[j]<a[j+1])
j=j+1;
}
if(v>=a[j])
heap=1;
else
{
a[k]=a[j];
k=j;
}
}
a[k]=v;
}

2. Design, develop and execute a program in C to create a Binary tree and perform the
following operation inorder, preorder and postorder traversals.

#include <stdlib.h>
typedef struct tnode
{
int data;
struct tnode *right,*left;
}TNODE;

TNODE *CreateBST(TNODE *, int);


void Inorder(TNODE *);
void Preorder(TNODE *);
void Postorder(TNODE *);
main()
{
TNODE *root=NULL; /* Main Program */
int opn,elem,n,i;
do
{
clrscr();
printf("\n Binary Search Tree Operations \n\n");
printf("\n Press 1-Creation of BST");
printf("\n 2-Traverse in Inorder");
printf("\n 3-Traverse in Preorder");
printf("\n 4-Traverse in Postorder");
printf("\n 5-Exit\n");
printf("\n Your option ? ");
scanf("%d",&opn);
switch(opn)
{
case 1: root=NULL;
printf("\n\nBST for How Many Nodes ?");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
printf("\nRead the Data for Node %d ?",i);
scanf("%d",&elem);
root=CreateBST(root,elem);
}
printf("\nBST with %d nodes is ready to Use!!\n",n); break;
case 2: printf("\n BST Traversal in INORDER \n");
Inorder(root); break;
case 3: printf("\n BST Traversal in PREORDER \n");
Preorder(root); break;
case 4: printf("\n BST Traversal in POSTORDER \n");
Postorder(root); break;
case 5: printf("\n\n Terminating \n\n"); break;
default: printf("\n\nInvalid Option !!! Try Again !! \n\n"); break;
}
printf("\n\n\n\n Press a Key to Continue . . . ");
getch();
}while(opn != 5);
}

TNODE *CreateBST(TNODE *root, int elem)


{
if(root == NULL)
{
root=(TNODE *)malloc(sizeof(TNODE));
root->left= root->right = NULL;
root->data=elem;
return root;
}
else
{
if( elem < root->data )
root->left=CreateBST(root->left,elem);
else
if( elem > root->data )
root->right=CreateBST(root->right,elem);
else
printf(" Duplicate Element !! Not Allowed !!!");
return(root);
}
}
void Inorder(TNODE *root)
{
if( root != NULL)
{
Inorder(root->left);
printf(" %d ",root->data);
Inorder(root->right);
}
}

void Preorder(TNODE *root)


{
if( root != NULL)
{
printf(" %d ",root->data);
Preorder(root->left);
Preorder(root->right);
}
}

void Postorder(TNODE *root)


{
if( root != NULL)
{
Postorder(root->left);
Postorder(root->right);
printf(" %d ",root->data);
}
}

A Heap is a special Tree-based data structure in which the tree is a complete binary tree. Since a
heap is a complete binary tree, a heap with N nodes has log N height. It is useful to remove the
highest or lowest priority element. It is typically represented as an array. There are two types of
Heaps in the data structure.
Min-Heap

In a Min-Heap the key present at the root node must be less than or equal among the keys present
at all of its children. The same property must be recursively true for all sub-trees in that Binary
Tree. In a Min-Heap the minimum key element present at the root. Below is the Binary Tree that
satisfies all the property of Min Heap.

Max Heap
In a Max-Heap the key present at the root node must be greater than or equal among the keys
present at all of its children. The same property must be recursively true for all sub-trees in that
Binary Tree. In a Max-Heap the maximum key element present at the root. Below is the Binary
Tree that satisfies all the property of Max Heap.
Expression Tree
The expression tree is a binary tree in which each internal node corresponds to the operator and
each leaf node corresponds to the operand so for example expression tree for 3 + ((5+9)*2)
would be:

Inorder traversal of expression tree produces infix version of given postfix expression (same with
postorder traversal it gives postfix expression)

Construction of Expression Tree:


Now For constructing an expression tree we use a stack. We loop through input expression and
do the following for every character.
1. If a character is an operand push that into the stack
2. If a character is an operator pop two values from the stack make them its child and
push the current node again.

In the end, the only element of the stack will be the root of an expression tree.

Examples:
Input: A B C*+ D/
Output: A + B * C / D

Expression tree Program and tree traversals for the expression tree
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

struct node
{
char info;
struct node *left;
struct node *right;
};

typedef struct node *NODE;

struct stack
{
int top;
NODE data[10];
};

typedef struct stack STACK;

int preced(char item){


switch(item){
case '^': return 5;
case '*':
case '/': return 3;
case '+':
case '-': return 1;
}
}

void preorder(NODE root){


if(root != NULL){
printf("%c\t", root->info);
preorder(root->left);
preorder(root->right);
}
}

void inorder(NODE root){


if(root != NULL){
inorder(root->left);
printf("%c\t", root->info);
inorder(root->right);
}
}

void postorder(NODE root){


if(root != NULL){
postorder(root->left);
postorder(root->right);
printf("%c\t", root->info);
}
}

void push(STACK *s, NODE temp){


s->data[++(s->top)] = temp;
}

NODE pop(STACK *s){


return (s->data[(s->top)--]);
}

NODE createnode(char item)


{
NODE temp;
temp = (NODE)malloc(sizeof(struct node));
temp->info = item;
temp->left = NULL;
temp->right = NULL;
return temp;
}

NODE createExpTree(char expr[20])


{
STACK tree, operator;
tree.top = -1;
operator.top = -1;
char symbol;
int i;
NODE temp, t, l, r;

for (i=0; expr[i] != '\0'; i++)


{
symbol = expr[i];
temp = createnode(symbol);
if(isalnum(symbol))
push(&tree, temp);
else{
if(operator.top == -1)
push(&operator, temp);
else{
while(operator.top != -1 && preced((operator.data[operator.top])->info) >=
preced(symbol))
{
t = pop(&operator);
r = pop(&tree);
l = pop(&tree);
t->right = r;
t->left = l;
push(&tree, t);
}
push(&operator, temp);
}
}
}

while(operator.top != -1){
t = pop(&operator);
r = pop(&tree);
l = pop(&tree);
t->right = r;
t->left = l;
push(&tree, t);
}

return pop(&tree);
}

int main()
{
NODE root = NULL;
char expr[20];
printf("Read expression\n");
scanf("%s", expr);
root = createExpTree(expr);
printf("\nInorder::");
inorder(root);
printf("\nPreorder:");
preorder(root);
printf("\nPostorder:");
postorder(root);
return 0;
}

Question Bank

1. Define the following with an example


1. Binary tree
2. Complete binary tree
3. Almost complete binary tree
4. Binary search tree
5. Depth of a tree
2. Given the following graph, write the inorder, preorder and postorder traversals.

3. In brief describe any 4 applications of trees.


4. Construct a binary tree from the traversal order given below:
1. PREORDER = A B D E F C G H L J K
2. INORDER = D B F E A G C L J H K
5. Construct a binary tree for: ((6 + (3 - 2) * 5) ^2 + 3).
6. Write c function for the following tree traversals:

i. Inorder ii) Preorder iii) Postorder

7. What is a tree? Explain

i. Root tree
ii. Degree
iii. Sibling
iv. Depth of a tree and give example
8. What is a binary tree? State the properties? How it is represented using array and linked list
give example.

9. Define max heap? Write a C function to insert an item into max heap.

10. For any non empty binary tree T if no is the number of leaf nodes and n2 the number of
nodes of degree 2. Then prove that n0=n2+1.
11. Explain the different tree traversal methods.
12. What is binary tree? Explain the different operations performed on binary tree.
13. Explain the different schemes of representation of binary tree.

14. Define the following with a suitable example.


i) Binary tree
ii) Degree of a binary tree
iii) Level of a binary tree

iv) Sibling.
15. Explain the following with an example:
1. i) Forest ii) graph iii) winner tree.
16. Describe the binary search tree with an example. Write an iterative function to search for
a key value in a binary search tree.
17. Explain the following with an example

i. Selection trees
ii. Forest tree and its traversals

18. Describe the binary search tree with an example. Write a recursive function to search for
a key value in a binary search tree.
19. Construct an inorder tree for the following elements. 66, 56, 12, 34, 78, 98, 12,-56, 4, 18.
20. Explain selection trees, with suitable example
21. What is a forest? With a suitable example illustrate how you transform a forest into a
binary tree.

You might also like