KEMBAR78
binary tree.pptx
NON-LINEAR
DATA STRUCTURES
Bhavyasree T
DoSR in MCA
Tumkur University
Contents
 Linear v/s Non-linear Data Structures
 Binary Trees
 Terminologies of Binary Trees
 Binary Tree Representation
 Types of Binary Trees
 Strictly Binary Tree
 Complete Binary Tree
 Almost Complete Binary Tree
 Binary Search Tree
 BST operations – traversal, searching, insertion, deletion
 Threaded Binary Tree and its types
 Expression Tree – construction
Linear and Non-Linear Data Structure
Linear Data Structure:
 The data items are stored in sequential order.
 Traversal is linear in nature.
 Easy to implement.
Ex: Arrays, Stacks, Queues, Linked List.
Non-Linear Data Structure:
 The data items are stored based on hierarchical
relationship among them.
 Traversal of nodes is non-linear in nature.
 Difficult to implement.
Ex: Trees, Graphs.
TREES
DEFINITION :
 A tree is non-primitive, non-linear data
structure.
 A tree is a data structure that represents
hierarchical relationships between individual
data items.
 Tree is an acyclic graph.
FOREST
It is a set of disjoint trees. In a given tree, if the root node is removed,
then it becomes a forest.
A
B C D
E F G H I
In the above tree, we have forest with three trees .
B
E F
C
G
D
H I
TREE
 It consists of a finite set of elements called nodes, and a
finite set of lines called branches, that connects the
nodes.
 The number of branches associated with a node is the
degree of the node.
 The number of branches (edges) leaving a node is
called an outdegree of that node.
 The number of branches (edges) entering a node is
called an indegree of that node.
TERMINOLOGIES
 Binary Tree: A binary tree is a finite set of elements
that is either empty or is partitioned into three
disjoint subsets:
- The first subset contains a single element called
the ROOT of the tree.
- The other two subsets are themselves binary trees,
called the LEFT and RIGHT subtrees of the
original tree.
 NODE : Each element of a binary tree is called a
node of the tree.
A
B E
C D F
Left subtree Right subtree
BINARY TREE
Note: A node in a binary tree can have no more than two subtrees.
TERMINOLOGIES
Parent:
A node is a parent if it has successor nodes i.e, if it has an outdegree
greater than zero.
Child:
A node with a predecessor is a child. A child node has an indegree of
one.
Root:
A node with no predecessor is called as a root node.
Leaf /Terminal Node (External Node) :
A leaf is any node with an outdegree of zero, i.e, a node with no
successors.
or
A Node that has no child is called a leaf node.
Binary Trees
A
B C
D E F
G
H I
LEVEL 0
LEVEL 1
LEVEL 2
LEVEL 3
Root: A Siblings: {D, E}, {B, C}, {H, I}
Parents: A, B, C, E, F Leaves: D, G, H, I
Children: B, C, D, E, G, F, H, I Internal nodes: B, C, E, F
TERMINOLOGIES
 Ancestor: Node n1 is an ancestor of node n2 if n1 is either
the parent of n2 or parent of some ancestor of n2.
EX: A is the ancestor of all nodes
E is the ancestor of G
B is the ancestor of D, E, G
C is the ancestor of F , H, I
 Descendants: The nodes in the path below the parent .
Ex: All the nodes below A are called descendants of A (i,e,
B, C, D, E, F, G, H, I) A
B C
D E F
G H I
TERMINOLOGIES
 Left Descendant:
Node n2 is a left descendant of node n1 if n2 is either the
left child of n1 or a descendant of left child of n1.
Ex: B is the left descendant of A.
D is the left descendant of B.
B, D, E, G are left descendants of A.
A
B C
D E F
G H I
TERMINOLOGIES
 Right Descendant:
Node n2 is a right descendant of node n1 if n2 is either the
right child of n1 or a descendant of right child of n1.
Ex: C is the right descendant of A.
I is the right descendant of F.
C, F, H, I are right descendants of A.
A
B C
D E F
G H I
TERMINOLOGIES
 Siblings : Two nodes having the same parent.
Ex:
Here, A is the Parent of B and C, B and C are children of A,
B and C are siblings.
A
C
B
TERMINOLOGIES
 Level of a node:
- The root of a tree has level 0(zero)
- Level of any other node in the tree is one more than level
of its parent.
Ex: A is at level 0.
B and C are at level 1.
D,E and F are at level 2.
G,H and I are at level 3.
It is the distance of a node from the root.
A
B C
D E F
G H I
TERMINOLOGIES
 Depth /Height of a Binary tree:
The maximum level of any leaf in the tree.
In below fig, depth is 3.
A
B C
D E F
G H I
Binary Tree Representation
Binary trees can be represented in 2 ways
in memory. They are:
1. Array representation
2. Linked list representation.
Binary Tree Representation
 Array Representation:
A
B
D
C
E F
G
A B C E
D F G
0 1 2 4
3 5 6 7 8 9 10 11 1213 15
14
A[i]
i
If the height of the binary tree is d then the array index ranges from
0 to 2d+1-1.
For the above binary tree, the array index ranges from 0 to 23+1-1
i.e., 0 to 15.
If P is the parent, then the left and right child are at the position
2P+1 and 2P+2 respectively.
Binary Tree Representation
 Linked List Representation:
In linked representation, each node N of the binary tree
will contain three fields:
1. Info
2. Left child
3. Right child
Structure definition for node in a Binary Tree :
typedef struct node
{
int data;
struct node *lchild, *rchild;
}NODE;
info
lchild rchild
Binary Tree Representation
 Linked List Representation:
consider the following binary tree
Linked representation :
A
B
D
C
E
F
G
A
C
B
D
G
E F
21
Binary Tree Traversal
 Traversing is a method of visiting each node of a
tree exactly once in a some order.
 Three Methods for Binary Tree traversal:
 Inorder Traversal
 Preorder Traversal
 Postorder Traversal
Binary Tree Traversal
 Inorder Traversal (Symmetric order) :
To traverse a non-empty binary tree in inorder :
1. Recursively traverse the left subtree in inorder
2. Visit the root
3. Recursively traverse the right subtree in inorder.
Example:
H
G
D
Inorder : E C F A G D H
F
E
A
C
2
1 3
Left subtree Right subtree
LNR
Binary Tree Traversal
 Preorder Traversal (Depth-First order) :
To traverse a non-empty binary tree in preorder :
1. Visit the root
2. Recursively traverse the left subtree in preorder
3. Recursively traverse the right subtree in preorder.
Example:
H
G
Preorder : A C E F D G H
F
E
A
C D
1
2 3
Left subtree Right subtree
NLR
Binary Tree Traversal
 Postorder Traversal :
To traverse a non-empty binary tree in postorder :
1. Recursively traverse the left subtree in postorder.
2. Recursively traverse the right subtree in postorder.
3. Visit the root.
Example:
H
G
Postorder : E F C G H D A
F
E
A
C D
3
1 2
Left subtree Right subtree
LRN
PROBLEM:
Given the following Inorder and predorder traversals, construct the binary tree:
Inorder: ECFAGDH
Preorder: ACEFDGH
Inorder: ECF A GDH
Preorder: ACEFDGH
A
ECF GDH
Inorder: ECF A GDH
Preorder: ACEFDGH
A
GDH
Inorder: ECF A GDH
Preorder: ACEFDGH
A
C
E F
C
E F
D
G H
PROBLEM:
Given the following Inorder and postorder traversals, construct the binary tree:
Inorder: ECFAGDH
Postorder: EFCGHDA
Inorder: ECF A GDH
Postorder: EFCGHDA
A
ECF GDH
Inorder: ECF A GDH
Postorder: EFCGHDA
A
GDH
Inorder: ECF A GDH
Postorder: EFCGHDA
A
C
E F
C
E F
D
G H
TYPES OF BINARY TREES
 Strictly Binary tree
 Complete Binary tree
 Almost complete binary tree
 Binary Search tree
 Threaded Binary tree
 Expression tree
 Strictly Binary Tree :
If every non-leaf node in a binary tree has non empty
left and right sub trees, the tree is termed as strictly
binary tree.
Ex:
A
C
B
D
F
E
G
E
A
B C
G
D
F
 Complete Binary Tree:
A completely binary tree of depth d is the strictly
binary tree, all of whose leaves are at level d.
Ex: Complete binary tree of depth 3.
A
B C
D E G
F
I
H L
J M O
N
K
 Almost Complete Binary Tree:
A binary tree of depth d is an almost complete binary
tree if:
- Any node nd at level less than d-1 has two children.
(Total no. of nodes at level d-1 should be 2d-1).
- The total number of nodes at level d may be equal to 2d.
If total number of nodes at level d is less than 2d,then
the nodes should be present only from left to right.
Ex:
A
B C
D E F G
H I
A
B C
D F G
H I
E
J
 Check whether the following Binary trees are strictly
binary trees or almost complete binary trees:
A
B C
D E F G
H I
A
B
C
D E
F G
J K
Fig a. Fig b.
NOTE:
• If a binary tree contains m nodes at level L , then it
contains atmost 2m nodes at level L+1.
• Since binary tree can contain atmost one node at
level 0(root node), it can contain 2L nodes at level L.
• A strictly binary tree with n leaves always contain
2n-1 nodes.
Nodes= (2 * 5) – 1 = 9
A
B C
D E F G
H I
• The total number of nodes in a complete binary tree
of depth d equals the sum of number of nodes at each
level between 0 (zero) and d.
Ex: In the fig: Tn= 20 + 21 + 22 + 23 = 15 nodes.
• In a complete binary tree of depth d, there are 2d leaf
nodes and 2d -1 nonleaf nodes.
Total No. of nodes = 2d+1 - 1.
A
B C
D E G
F
I
H L
J M O
N
K
Binary Search Tree (Binary Sorted Tree) :
 Suppose T is a binary tree. Then T is called a binary search tree
if each node of the tree has the following property :
the value of each node is greater than every value in the left
subtree of that node and is less than or equal to every value in
the right subtree of that node.
 Let X be a node in a binary search tree .
If K1 is a node in the left subtree of x,then info(K1)<info(X).
If K2 is a node in the right subtree of X , then
info(X)<=info(K2)
BINARY SEARCH TREE
K1<X<=K2
K1 K2
5
 Example BSTs:
3 7
2 4 8
2
3
7
5
4
8
Examine whether the below given tree is a BST or not:
925
202
911
240
912
245
363
912>911 in left subtree for node 911.
Hence, this sequence doesn’t form
BST.
BSTs of height 2, 3, 4, 5, 6 for the following set of keys:
1, 4, 5, 10, 16, 17, 21
10
4 17
1 5 16 21
16
10 17
17
16 21
4
1 5
21
10
4
1 5
10
4
1
5
17
16 21
10
4
1 5
17
16
21
or
10
4
1
5
17
16
21
10
17
21
16
4
5
1
HEIGHT 2 HEIGHT 3
HEIGHT 4
HEIGHT 5
or
HEIGHT 6
Operations On Binary Search Tree (BST)
 Traversal
 Searching
 Insertion
TRAVERSAL:
10
4 17
1 5 16 21
INORDER: 1, 4, 5, 10, 16, 17, 21
PREORDER: 10, 4, 1, 5, 17, 16, 21
POSTORDER: 1, 5, 4, 16, 21, 17, 10
10
4 17
1 5 16 21
SEARCHING: int search(NODE *root, int key)
{
while(root!=NULL)
{
if(key == root->info)
return(1);
else if(key < root -> info)
root = root ->lchild;
else
root = root -> rchild;
}
return(0);
}
/*Non-recursive function*/
NODE * search(NODE *root, int key)
{
if(root==NULL || root->info==key)
return root;
if(key < root->info)
return(search(root -> lchild,key));
return(search(root -> rchild,key));
}
/*Recursive function*/
INSERTION:
GIVE THE VARIOUS STEPS INVOLVED IN CREATING A BST FOR
THE FOLLOWING SEQUENCE: 70, 35, 65, 50, 75, 90, 20
70
35 75
20 65
50
90
70
35 75
65
50
90
70
35 75
65
50
70
35
65
50
70
35
65
70
35
70
DELETION:
70
35 75
20 65
50
90
70
35 75
20 65
50
KEY
70
35 75
20 65
50
90
70
35
20 65
50
90
KEY
DELETION:
70
75
20 65
50
70
75
20 65
50
KEY
90
35
1. Obtain the inorder successor of the node to be deleted.
2. Attach the left subtree of the node to be deleted to left of inorder
successor.
3. Obtain right subtree of the node to be deleted say q.
4. Attach q to parent of node to be deleted.
1. SUCCESSOR
35
2
3. q
4
70
75
20
65
50
90
90
THREADED BINARY TREE
 In linked representation of a binary tree, approximately half of the
entries in the pointer fields i.e, lchild and rchild contain NULL . This
space may be more efficiently used by replacing certain NULL
pointers by some special pointers which points to the successor or
to the predecessor.
 These special pointers are called THREADS, and binary trees with
such pointers are called Threaded Binary Trees.
 The threads are represented by dotted lines to distinguish between
the threads and ordinary links used to connect the left subtree &
right subtree .
A
C
B
D F
G
E
A
C
D F
G
E
B
Inorder : D B A E G C F
Fig (a) Fig (b)
In-Threaded Binary Tree
An Inorder Threading of a Binary Tree /
In-Threaded Binary Tree
Right In-Threaded Binary Tree
A binary tree is threaded, based on the traversal technique.
 If the right link of a node is NULL and if it is replaced by
the address of the inorder successor then the tree is said
to be Right in-threaded binary tree.
 Example:
A
C
B
D F
G
E
Inorder : D B A E G C F
 If the left link of a node is NULL and if it is replaced by
the address of the inorder predecessor, then the tree is
said to be Left in-threaded binary tree.
 Example:
A
C
B
D F
G
E
Inorder : D B A E G C F
Left In-Threaded Binary Tree
A Preorder Threading of a Binary Tree /Pre-Threaded Binary Tree
Right Pre-Threaded Binary Tree
 If the right link of a node is NULL and if it is replaced by
the address of the preorder successor then the tree is said
to be Right Pre-threaded binary tree.
 Example:
A
C
B
D F
G
E
Preorder : A B D C E G F
 If the left link of a node is NULL and if it is replaced by
the address of the preorder predecessor, then the tree is
said to be Left Pre-threaded binary tree.
 Example:
A
C
B
D F
G
E
Preorder : A B D C E G F
A Preorder Threading of a Binary Tree /Pre-Threaded Binary Tree
Left Pre-Threaded Binary Tree
 If the right link of a node is NULL and if it is replaced by
the address of the postorder successor then the tree is
said to be Right Post-threaded binary tree.
 Example:
A
C
B
D F
G
E
Postorder : D B G E F C A
A Postorder Threading of a Binary Tree /Post-Threaded Binary Tree
Right Post-Threaded Binary Tree
 If the left link of a node is NULL and if it is replaced by
the address of the postorder predecessor, then the tree is
said to be Left Post-threaded binary tree.
 Example:
A
C
B
D F
G
E
Postorder : D B G E F C A
A Postorder Threading of a Binary Tree /Post-Threaded Binary Tree
Left Post-Threaded Binary Tree
Representing an Expression Containing Operands and
Binary Operators (+, -, *, / ,^ ETC) :
 An Infix expression consisting of operators and operands
can be represented using a binary tree .
 A node representing an operator is a nonleaf node ,
whereas a node representing an operand is a leaf node.
EXPRESSION TREE
 Example1:
Inorder : A + B * C
Preorder : + A * B C
Postorder : A B C * + +
A *
C
B
EXPRESSION TREE
 Example 2:
Inorder :
A+((B-C)*(D^(E+F)))
Preorder :
+A*-BC^D+EF
Postorder :
ABC-DEF+^*+
+
A *
C
B D
E F
^
+
-
CREATION OF BINARY TREE FOR POSTFIX EXPRESSION
Scan the symbol from left to right and perform the following operations:
1. Create a node for the scanned symbol.
2. If the scanned symbol is an operand then push the corresponding
node onto stack.
3. If the scanned symbol is an operator, then pop top two nodes from
stack. First popped is attached to right of the node with scanned
operator. Second popped is attached to the left of the node with
scanned operator.
4. Push the node corresponding to the operator onto stack.
5. Repeat step1 to step4 till all the symbols of postfix expression are
scanned. Once end of input is encountered, the address of root
node of the expression tree is on the top of the stack.
EXAMPLE: Consider the following postfix expression: a b + c d e + * *
a b +
a b
+
a b
c d e
+
a b
c +
d e
+
a b +
d e
c
*
EXAMPLE: Consider the following postfix expression: a b + c d e + * *
+
a b
+
d e
c
*
*
Once all the symbols are scanned, the address of root node of the
expression tree will be on the top of the stack.
CREATION OF BINARY TREE FOR PREFIX EXPRESSION
Scan the symbol from right to left and perform the following operations:
1. Create a node for the scanned symbol.
2. If the scanned symbol is an operand then push the corresponding
node onto stack.
3. If the scanned symbol is an operator, then pop top two nodes from
stack. First popped is attached to left of the node with scanned
operator. Second popped is attached to the right of the node with
scanned operator.
4. Push the node corresponding to the operator onto stack.
5. Repeat step1 to step4 till all the symbols of postfix expression are
scanned. Once end of input is encountered, the address of root
node of the expression tree is on the top of the stack.
#include<stdio.h>
#include<stdlib.h>
typedef struct node
{
int info;
struct node *lchild,*rchild;
}NODE;
NODE * insert(NODE *root,int data)
{
NODE *newnode,*temp,*parent;
newnode=(NODE*)malloc(sizeof(NODE));
newnode->lchild=newnode->rchild=NULL;
newnode->info=data;
if(root==NULL)
root=newnode;
else
{
temp=root;
while(temp!=NULL)
{
parent=temp;
if(data > temp->info)
temp=temp->rchild;
else if(data < temp->info)
temp=temp->lchild;
else
{
printf("nData %d is already existing in the BST",data);
return(root);
}
}
if(data > parent->info)
parent->rchild=newnode;
else
parent->lchild=newnode;
}
printf(“n%d is inserted into BST”,data);
return(root);
}
Program 12: Develop a C program to perform the following operations:
a) Construct a BST of integers b) Traverse in Inorder c) Delete a given node from the BST
Program 12: Develop a C program to perform the following operations:
a) Construct a BST of integers b) Traverse in Inorder c) Delete a given node from the BST
void inorder(NODE *root)
{
if(root==NULL)
return;
inorder(root->lchild);
printf("%d ",root->info);
inorder(root->rchild);
}
NODE *del_key(NODE *root,int key)
{
NODE *cur,*q,*parent,*successor;
parent=NULL,cur=root;
while(cur!=NULL)
{
if(cur->info==key)
break;
parent=cur;
cur= (key<cur->info)?cur->lchild:cur->rchild;
}
if(cur==NULL)
{
printf("nKey %d is not found",key);
return root;
}
if(cur->lchild==NULL)
q=cur->rchild;
else if(cur->rchild==NULL)
q=cur->lchild;
else
{
successor = cur->rchild;
while(successor->lchild != NULL)
successor = successor->lchild;
successor->lchild = cur->lchild;
q = cur->rchild;
}
Program 12: Develop a C program to perform the following operations:
a) Construct a BST of integers b) Traverse in Inorder c) Delete a given node from the BST
if (parent == NULL)
{
printf("n%d is deleted from BST",key);
free(cur);
return q;
}
if(cur == parent->lchild)
parent->lchild = q;
else
parent->rchild = q;
printf("n%d is deleted from BST",key);
free(cur);
return root;
}
scanf("%d",&choice);
switch(choice)
{
case 1: printf("nEnter data to be inserted: ");
scanf("%d",&data);
root=insert(root,data);
break;
case 2: if(root==NULL)
printf("nEmpty Tree");
else
{
printf("nInorder Traversal: ");
inorder(root);
}
break;
int main()
{
int choice,data,key;
NODE *root=NULL;
while(1)
{
printf("n1:Insert 2:Inorder 3:Delete 4:Exit");
printf("nEnter your choice: ");
Program 12: Develop a C program to perform the following operations:
a) Construct a BST of integers b) Traverse in Inorder c) Delete a given node from the BST
case 3: if(root==NULL)
printf("nEmpty Tree");
else
{
printf("nEnter the key to delete: ");
scanf("%d",&key);
root=del_key(root,key);
}
break;
case 4: exit(0);
default: printf("nInvalid choice");
}
}
return 0;
}
Program 13: Develop a C program to construct an expression tree for a given postfix
expression and evaluate the expression tree.
#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
#include<math.h>
typedef struct node
{
char info;
struct node *lchild,*rchild;
}NODE;
NODE * create_tree(char postfix[])
{
NODE *newnode, *stack[20];
int i, top = -1;
char ch;
for(i=0;postfix[i]!='0‘;i++)
{
ch=postfix[i];
newnode = (NODE*)malloc(sizeof(NODE));
newnode->info = ch;
newnode->lchild = newnode->rchild = NULL;
if(isalnum(ch))
stack[++top]=newnode;
else
{
newnode->rchild = stack[top--];
newnode->lchild = stack[top--];
stack[++top]=newnode;
}
}
return(stack[top--]);
}
Program 13: Develop a C program to construct an expression tree for a given postfix
expression and evaluate the expression tree.
float eval(NODE *root)
{
float num;
switch(root->info)
{
case '+' : return (eval(root->lchild) + eval(root->rchild));
case '-' : return (eval(root->lchild) - eval(root->rchild));
case '*' : return (eval(root->lchild) * eval(root->rchild));
case '/' : return (eval(root->lchild) / eval(root->rchild));
case '^' : return (pow(eval(root->lchild), eval(root->rchild)));
default: if(isalpha(root->info))
{
printf("n%c = ",root->info);
scanf("%f",&num);
return(num);
}
else
return(root->info - '0');
}
}
int main()
{
char postfix[30];
float res;
NODE * root = NULL;
printf("nEnter a valid Postfix expressionn");
scanf("%s",postfix);
root = create_tree(postfix);
res = eval (root);
printf("nResult = %f",res);
return 0;
}

binary tree.pptx

  • 1.
  • 2.
    Contents  Linear v/sNon-linear Data Structures  Binary Trees  Terminologies of Binary Trees  Binary Tree Representation  Types of Binary Trees  Strictly Binary Tree  Complete Binary Tree  Almost Complete Binary Tree  Binary Search Tree  BST operations – traversal, searching, insertion, deletion  Threaded Binary Tree and its types  Expression Tree – construction
  • 3.
    Linear and Non-LinearData Structure Linear Data Structure:  The data items are stored in sequential order.  Traversal is linear in nature.  Easy to implement. Ex: Arrays, Stacks, Queues, Linked List. Non-Linear Data Structure:  The data items are stored based on hierarchical relationship among them.  Traversal of nodes is non-linear in nature.  Difficult to implement. Ex: Trees, Graphs.
  • 4.
    TREES DEFINITION :  Atree is non-primitive, non-linear data structure.  A tree is a data structure that represents hierarchical relationships between individual data items.  Tree is an acyclic graph.
  • 5.
    FOREST It is aset of disjoint trees. In a given tree, if the root node is removed, then it becomes a forest. A B C D E F G H I In the above tree, we have forest with three trees . B E F C G D H I
  • 6.
    TREE  It consistsof a finite set of elements called nodes, and a finite set of lines called branches, that connects the nodes.  The number of branches associated with a node is the degree of the node.  The number of branches (edges) leaving a node is called an outdegree of that node.  The number of branches (edges) entering a node is called an indegree of that node.
  • 7.
    TERMINOLOGIES  Binary Tree:A binary tree is a finite set of elements that is either empty or is partitioned into three disjoint subsets: - The first subset contains a single element called the ROOT of the tree. - The other two subsets are themselves binary trees, called the LEFT and RIGHT subtrees of the original tree.  NODE : Each element of a binary tree is called a node of the tree.
  • 8.
    A B E C DF Left subtree Right subtree BINARY TREE Note: A node in a binary tree can have no more than two subtrees.
  • 9.
    TERMINOLOGIES Parent: A node isa parent if it has successor nodes i.e, if it has an outdegree greater than zero. Child: A node with a predecessor is a child. A child node has an indegree of one. Root: A node with no predecessor is called as a root node. Leaf /Terminal Node (External Node) : A leaf is any node with an outdegree of zero, i.e, a node with no successors. or A Node that has no child is called a leaf node.
  • 10.
    Binary Trees A B C DE F G H I LEVEL 0 LEVEL 1 LEVEL 2 LEVEL 3 Root: A Siblings: {D, E}, {B, C}, {H, I} Parents: A, B, C, E, F Leaves: D, G, H, I Children: B, C, D, E, G, F, H, I Internal nodes: B, C, E, F
  • 11.
    TERMINOLOGIES  Ancestor: Noden1 is an ancestor of node n2 if n1 is either the parent of n2 or parent of some ancestor of n2. EX: A is the ancestor of all nodes E is the ancestor of G B is the ancestor of D, E, G C is the ancestor of F , H, I  Descendants: The nodes in the path below the parent . Ex: All the nodes below A are called descendants of A (i,e, B, C, D, E, F, G, H, I) A B C D E F G H I
  • 12.
    TERMINOLOGIES  Left Descendant: Noden2 is a left descendant of node n1 if n2 is either the left child of n1 or a descendant of left child of n1. Ex: B is the left descendant of A. D is the left descendant of B. B, D, E, G are left descendants of A. A B C D E F G H I
  • 13.
    TERMINOLOGIES  Right Descendant: Noden2 is a right descendant of node n1 if n2 is either the right child of n1 or a descendant of right child of n1. Ex: C is the right descendant of A. I is the right descendant of F. C, F, H, I are right descendants of A. A B C D E F G H I
  • 14.
    TERMINOLOGIES  Siblings :Two nodes having the same parent. Ex: Here, A is the Parent of B and C, B and C are children of A, B and C are siblings. A C B
  • 15.
    TERMINOLOGIES  Level ofa node: - The root of a tree has level 0(zero) - Level of any other node in the tree is one more than level of its parent. Ex: A is at level 0. B and C are at level 1. D,E and F are at level 2. G,H and I are at level 3. It is the distance of a node from the root. A B C D E F G H I
  • 16.
    TERMINOLOGIES  Depth /Heightof a Binary tree: The maximum level of any leaf in the tree. In below fig, depth is 3. A B C D E F G H I
  • 17.
    Binary Tree Representation Binarytrees can be represented in 2 ways in memory. They are: 1. Array representation 2. Linked list representation.
  • 18.
    Binary Tree Representation Array Representation: A B D C E F G A B C E D F G 0 1 2 4 3 5 6 7 8 9 10 11 1213 15 14 A[i] i If the height of the binary tree is d then the array index ranges from 0 to 2d+1-1. For the above binary tree, the array index ranges from 0 to 23+1-1 i.e., 0 to 15. If P is the parent, then the left and right child are at the position 2P+1 and 2P+2 respectively.
  • 19.
    Binary Tree Representation Linked List Representation: In linked representation, each node N of the binary tree will contain three fields: 1. Info 2. Left child 3. Right child Structure definition for node in a Binary Tree : typedef struct node { int data; struct node *lchild, *rchild; }NODE; info lchild rchild
  • 20.
    Binary Tree Representation Linked List Representation: consider the following binary tree Linked representation : A B D C E F G A C B D G E F
  • 21.
    21 Binary Tree Traversal Traversing is a method of visiting each node of a tree exactly once in a some order.  Three Methods for Binary Tree traversal:  Inorder Traversal  Preorder Traversal  Postorder Traversal
  • 22.
    Binary Tree Traversal Inorder Traversal (Symmetric order) : To traverse a non-empty binary tree in inorder : 1. Recursively traverse the left subtree in inorder 2. Visit the root 3. Recursively traverse the right subtree in inorder. Example: H G D Inorder : E C F A G D H F E A C 2 1 3 Left subtree Right subtree LNR
  • 23.
    Binary Tree Traversal Preorder Traversal (Depth-First order) : To traverse a non-empty binary tree in preorder : 1. Visit the root 2. Recursively traverse the left subtree in preorder 3. Recursively traverse the right subtree in preorder. Example: H G Preorder : A C E F D G H F E A C D 1 2 3 Left subtree Right subtree NLR
  • 24.
    Binary Tree Traversal Postorder Traversal : To traverse a non-empty binary tree in postorder : 1. Recursively traverse the left subtree in postorder. 2. Recursively traverse the right subtree in postorder. 3. Visit the root. Example: H G Postorder : E F C G H D A F E A C D 3 1 2 Left subtree Right subtree LRN
  • 25.
    PROBLEM: Given the followingInorder and predorder traversals, construct the binary tree: Inorder: ECFAGDH Preorder: ACEFDGH Inorder: ECF A GDH Preorder: ACEFDGH A ECF GDH Inorder: ECF A GDH Preorder: ACEFDGH A GDH Inorder: ECF A GDH Preorder: ACEFDGH A C E F C E F D G H
  • 26.
    PROBLEM: Given the followingInorder and postorder traversals, construct the binary tree: Inorder: ECFAGDH Postorder: EFCGHDA Inorder: ECF A GDH Postorder: EFCGHDA A ECF GDH Inorder: ECF A GDH Postorder: EFCGHDA A GDH Inorder: ECF A GDH Postorder: EFCGHDA A C E F C E F D G H
  • 27.
    TYPES OF BINARYTREES  Strictly Binary tree  Complete Binary tree  Almost complete binary tree  Binary Search tree  Threaded Binary tree  Expression tree
  • 28.
     Strictly BinaryTree : If every non-leaf node in a binary tree has non empty left and right sub trees, the tree is termed as strictly binary tree. Ex: A C B D F E G E A B C G D F
  • 29.
     Complete BinaryTree: A completely binary tree of depth d is the strictly binary tree, all of whose leaves are at level d. Ex: Complete binary tree of depth 3. A B C D E G F I H L J M O N K
  • 30.
     Almost CompleteBinary Tree: A binary tree of depth d is an almost complete binary tree if: - Any node nd at level less than d-1 has two children. (Total no. of nodes at level d-1 should be 2d-1). - The total number of nodes at level d may be equal to 2d. If total number of nodes at level d is less than 2d,then the nodes should be present only from left to right. Ex: A B C D E F G H I A B C D F G H I E J
  • 31.
     Check whetherthe following Binary trees are strictly binary trees or almost complete binary trees: A B C D E F G H I A B C D E F G J K Fig a. Fig b.
  • 32.
    NOTE: • If abinary tree contains m nodes at level L , then it contains atmost 2m nodes at level L+1. • Since binary tree can contain atmost one node at level 0(root node), it can contain 2L nodes at level L. • A strictly binary tree with n leaves always contain 2n-1 nodes. Nodes= (2 * 5) – 1 = 9 A B C D E F G H I
  • 33.
    • The totalnumber of nodes in a complete binary tree of depth d equals the sum of number of nodes at each level between 0 (zero) and d. Ex: In the fig: Tn= 20 + 21 + 22 + 23 = 15 nodes. • In a complete binary tree of depth d, there are 2d leaf nodes and 2d -1 nonleaf nodes. Total No. of nodes = 2d+1 - 1. A B C D E G F I H L J M O N K
  • 34.
    Binary Search Tree(Binary Sorted Tree) :  Suppose T is a binary tree. Then T is called a binary search tree if each node of the tree has the following property : the value of each node is greater than every value in the left subtree of that node and is less than or equal to every value in the right subtree of that node.  Let X be a node in a binary search tree . If K1 is a node in the left subtree of x,then info(K1)<info(X). If K2 is a node in the right subtree of X , then info(X)<=info(K2) BINARY SEARCH TREE K1<X<=K2 K1 K2
  • 35.
    5  Example BSTs: 37 2 4 8 2 3 7 5 4 8
  • 36.
    Examine whether thebelow given tree is a BST or not: 925 202 911 240 912 245 363 912>911 in left subtree for node 911. Hence, this sequence doesn’t form BST.
  • 37.
    BSTs of height2, 3, 4, 5, 6 for the following set of keys: 1, 4, 5, 10, 16, 17, 21 10 4 17 1 5 16 21 16 10 17 17 16 21 4 1 5 21 10 4 1 5 10 4 1 5 17 16 21 10 4 1 5 17 16 21 or 10 4 1 5 17 16 21 10 17 21 16 4 5 1 HEIGHT 2 HEIGHT 3 HEIGHT 4 HEIGHT 5 or HEIGHT 6
  • 38.
    Operations On BinarySearch Tree (BST)  Traversal  Searching  Insertion TRAVERSAL: 10 4 17 1 5 16 21 INORDER: 1, 4, 5, 10, 16, 17, 21 PREORDER: 10, 4, 1, 5, 17, 16, 21 POSTORDER: 1, 5, 4, 16, 21, 17, 10
  • 39.
    10 4 17 1 516 21 SEARCHING: int search(NODE *root, int key) { while(root!=NULL) { if(key == root->info) return(1); else if(key < root -> info) root = root ->lchild; else root = root -> rchild; } return(0); } /*Non-recursive function*/ NODE * search(NODE *root, int key) { if(root==NULL || root->info==key) return root; if(key < root->info) return(search(root -> lchild,key)); return(search(root -> rchild,key)); } /*Recursive function*/
  • 40.
    INSERTION: GIVE THE VARIOUSSTEPS INVOLVED IN CREATING A BST FOR THE FOLLOWING SEQUENCE: 70, 35, 65, 50, 75, 90, 20 70 35 75 20 65 50 90 70 35 75 65 50 90 70 35 75 65 50 70 35 65 50 70 35 65 70 35 70
  • 41.
    DELETION: 70 35 75 20 65 50 90 70 3575 20 65 50 KEY 70 35 75 20 65 50 90 70 35 20 65 50 90 KEY
  • 42.
    DELETION: 70 75 20 65 50 70 75 20 65 50 KEY 90 35 1.Obtain the inorder successor of the node to be deleted. 2. Attach the left subtree of the node to be deleted to left of inorder successor. 3. Obtain right subtree of the node to be deleted say q. 4. Attach q to parent of node to be deleted. 1. SUCCESSOR 35 2 3. q 4 70 75 20 65 50 90 90
  • 43.
    THREADED BINARY TREE In linked representation of a binary tree, approximately half of the entries in the pointer fields i.e, lchild and rchild contain NULL . This space may be more efficiently used by replacing certain NULL pointers by some special pointers which points to the successor or to the predecessor.  These special pointers are called THREADS, and binary trees with such pointers are called Threaded Binary Trees.  The threads are represented by dotted lines to distinguish between the threads and ordinary links used to connect the left subtree & right subtree .
  • 44.
    A C B D F G E A C D F G E B Inorder: D B A E G C F Fig (a) Fig (b) In-Threaded Binary Tree An Inorder Threading of a Binary Tree / In-Threaded Binary Tree
  • 45.
    Right In-Threaded BinaryTree A binary tree is threaded, based on the traversal technique.  If the right link of a node is NULL and if it is replaced by the address of the inorder successor then the tree is said to be Right in-threaded binary tree.  Example: A C B D F G E Inorder : D B A E G C F
  • 46.
     If theleft link of a node is NULL and if it is replaced by the address of the inorder predecessor, then the tree is said to be Left in-threaded binary tree.  Example: A C B D F G E Inorder : D B A E G C F Left In-Threaded Binary Tree
  • 47.
    A Preorder Threadingof a Binary Tree /Pre-Threaded Binary Tree Right Pre-Threaded Binary Tree  If the right link of a node is NULL and if it is replaced by the address of the preorder successor then the tree is said to be Right Pre-threaded binary tree.  Example: A C B D F G E Preorder : A B D C E G F
  • 48.
     If theleft link of a node is NULL and if it is replaced by the address of the preorder predecessor, then the tree is said to be Left Pre-threaded binary tree.  Example: A C B D F G E Preorder : A B D C E G F A Preorder Threading of a Binary Tree /Pre-Threaded Binary Tree Left Pre-Threaded Binary Tree
  • 49.
     If theright link of a node is NULL and if it is replaced by the address of the postorder successor then the tree is said to be Right Post-threaded binary tree.  Example: A C B D F G E Postorder : D B G E F C A A Postorder Threading of a Binary Tree /Post-Threaded Binary Tree Right Post-Threaded Binary Tree
  • 50.
     If theleft link of a node is NULL and if it is replaced by the address of the postorder predecessor, then the tree is said to be Left Post-threaded binary tree.  Example: A C B D F G E Postorder : D B G E F C A A Postorder Threading of a Binary Tree /Post-Threaded Binary Tree Left Post-Threaded Binary Tree
  • 51.
    Representing an ExpressionContaining Operands and Binary Operators (+, -, *, / ,^ ETC) :  An Infix expression consisting of operators and operands can be represented using a binary tree .  A node representing an operator is a nonleaf node , whereas a node representing an operand is a leaf node.
  • 52.
    EXPRESSION TREE  Example1: Inorder: A + B * C Preorder : + A * B C Postorder : A B C * + + A * C B
  • 53.
    EXPRESSION TREE  Example2: Inorder : A+((B-C)*(D^(E+F))) Preorder : +A*-BC^D+EF Postorder : ABC-DEF+^*+ + A * C B D E F ^ + -
  • 54.
    CREATION OF BINARYTREE FOR POSTFIX EXPRESSION Scan the symbol from left to right and perform the following operations: 1. Create a node for the scanned symbol. 2. If the scanned symbol is an operand then push the corresponding node onto stack. 3. If the scanned symbol is an operator, then pop top two nodes from stack. First popped is attached to right of the node with scanned operator. Second popped is attached to the left of the node with scanned operator. 4. Push the node corresponding to the operator onto stack. 5. Repeat step1 to step4 till all the symbols of postfix expression are scanned. Once end of input is encountered, the address of root node of the expression tree is on the top of the stack.
  • 55.
    EXAMPLE: Consider thefollowing postfix expression: a b + c d e + * * a b + a b + a b c d e + a b c + d e + a b + d e c *
  • 56.
    EXAMPLE: Consider thefollowing postfix expression: a b + c d e + * * + a b + d e c * * Once all the symbols are scanned, the address of root node of the expression tree will be on the top of the stack.
  • 57.
    CREATION OF BINARYTREE FOR PREFIX EXPRESSION Scan the symbol from right to left and perform the following operations: 1. Create a node for the scanned symbol. 2. If the scanned symbol is an operand then push the corresponding node onto stack. 3. If the scanned symbol is an operator, then pop top two nodes from stack. First popped is attached to left of the node with scanned operator. Second popped is attached to the right of the node with scanned operator. 4. Push the node corresponding to the operator onto stack. 5. Repeat step1 to step4 till all the symbols of postfix expression are scanned. Once end of input is encountered, the address of root node of the expression tree is on the top of the stack.
  • 58.
    #include<stdio.h> #include<stdlib.h> typedef struct node { intinfo; struct node *lchild,*rchild; }NODE; NODE * insert(NODE *root,int data) { NODE *newnode,*temp,*parent; newnode=(NODE*)malloc(sizeof(NODE)); newnode->lchild=newnode->rchild=NULL; newnode->info=data; if(root==NULL) root=newnode; else { temp=root; while(temp!=NULL) { parent=temp; if(data > temp->info) temp=temp->rchild; else if(data < temp->info) temp=temp->lchild; else { printf("nData %d is already existing in the BST",data); return(root); } } if(data > parent->info) parent->rchild=newnode; else parent->lchild=newnode; } printf(“n%d is inserted into BST”,data); return(root); } Program 12: Develop a C program to perform the following operations: a) Construct a BST of integers b) Traverse in Inorder c) Delete a given node from the BST
  • 59.
    Program 12: Developa C program to perform the following operations: a) Construct a BST of integers b) Traverse in Inorder c) Delete a given node from the BST void inorder(NODE *root) { if(root==NULL) return; inorder(root->lchild); printf("%d ",root->info); inorder(root->rchild); } NODE *del_key(NODE *root,int key) { NODE *cur,*q,*parent,*successor; parent=NULL,cur=root; while(cur!=NULL) { if(cur->info==key) break; parent=cur; cur= (key<cur->info)?cur->lchild:cur->rchild; } if(cur==NULL) { printf("nKey %d is not found",key); return root; } if(cur->lchild==NULL) q=cur->rchild; else if(cur->rchild==NULL) q=cur->lchild; else { successor = cur->rchild; while(successor->lchild != NULL) successor = successor->lchild; successor->lchild = cur->lchild; q = cur->rchild; }
  • 60.
    Program 12: Developa C program to perform the following operations: a) Construct a BST of integers b) Traverse in Inorder c) Delete a given node from the BST if (parent == NULL) { printf("n%d is deleted from BST",key); free(cur); return q; } if(cur == parent->lchild) parent->lchild = q; else parent->rchild = q; printf("n%d is deleted from BST",key); free(cur); return root; } scanf("%d",&choice); switch(choice) { case 1: printf("nEnter data to be inserted: "); scanf("%d",&data); root=insert(root,data); break; case 2: if(root==NULL) printf("nEmpty Tree"); else { printf("nInorder Traversal: "); inorder(root); } break; int main() { int choice,data,key; NODE *root=NULL; while(1) { printf("n1:Insert 2:Inorder 3:Delete 4:Exit"); printf("nEnter your choice: ");
  • 61.
    Program 12: Developa C program to perform the following operations: a) Construct a BST of integers b) Traverse in Inorder c) Delete a given node from the BST case 3: if(root==NULL) printf("nEmpty Tree"); else { printf("nEnter the key to delete: "); scanf("%d",&key); root=del_key(root,key); } break; case 4: exit(0); default: printf("nInvalid choice"); } } return 0; }
  • 62.
    Program 13: Developa C program to construct an expression tree for a given postfix expression and evaluate the expression tree. #include<stdio.h> #include<stdlib.h> #include<ctype.h> #include<math.h> typedef struct node { char info; struct node *lchild,*rchild; }NODE; NODE * create_tree(char postfix[]) { NODE *newnode, *stack[20]; int i, top = -1; char ch; for(i=0;postfix[i]!='0‘;i++) { ch=postfix[i]; newnode = (NODE*)malloc(sizeof(NODE)); newnode->info = ch; newnode->lchild = newnode->rchild = NULL; if(isalnum(ch)) stack[++top]=newnode; else { newnode->rchild = stack[top--]; newnode->lchild = stack[top--]; stack[++top]=newnode; } } return(stack[top--]); }
  • 63.
    Program 13: Developa C program to construct an expression tree for a given postfix expression and evaluate the expression tree. float eval(NODE *root) { float num; switch(root->info) { case '+' : return (eval(root->lchild) + eval(root->rchild)); case '-' : return (eval(root->lchild) - eval(root->rchild)); case '*' : return (eval(root->lchild) * eval(root->rchild)); case '/' : return (eval(root->lchild) / eval(root->rchild)); case '^' : return (pow(eval(root->lchild), eval(root->rchild))); default: if(isalpha(root->info)) { printf("n%c = ",root->info); scanf("%f",&num); return(num); } else return(root->info - '0'); } } int main() { char postfix[30]; float res; NODE * root = NULL; printf("nEnter a valid Postfix expressionn"); scanf("%s",postfix); root = create_tree(postfix); res = eval (root); printf("nResult = %f",res); return 0; }