SlideShare a Scribd company logo
BINARY
TREES
Module 5
Contents
Binary Trees: Introduction and definition,
Node Representation of Binary Trees,
Internal and External Nodes,
Implicit Array Representation of Binary Trees,
Primitive operations on Binary Tree,
Threaded binary tree,
Binary search tree and its primitive operations,
General Expressions as Trees,
evaluating an expression tree,
constructing a Tree.
DEFINITION
• A tree is a finite set of one or more nodes such that
– There is a specially designated node called root.
– The remaining nodes are partitioned into n >= 0 disjoint set T1,…,Tn,
where each of these sets is a tree.
– T1,…,Tn are called the subtrees of the root
Introduction
Trees: Unlike Arrays, Linked Lists, Stack and queues, which are linear
data structures, trees are hierarchical data structures.
Tree Vocabulary: The topmost node is called root of the tree. The
elements that are directly under an element are called its children. The
element directly above something is called its parent. For example, ‘a’
is a child of ‘f’, and ‘f’ is the parent of ‘a’. Finally, elements with no
children are called leaves.
Why Trees?
1. One reason to use trees might be to store
information that naturally forms a hierarchy. For
example, the file system on a computer
2. Trees (with some ordering e.g., BST)
provide moderate access/search
(quicker than Linked List and slower
than arrays).
3. Trees provide moderate
insertion/deletion (quicker than Arrays
and slower than Unordered Linked
Lists).
4. Like Linked Lists and unlike Arrays,
Trees don’t have an upper limit on
Need for binary trees:
• In C, Binary trees have some exciting and useful
applications which can be implemented.
• With the help of a binary search tree, an element can be
found in a huge set because it is fast and efficient.
• Using binary trees, implementation of heapsort is easy.
• To store information in databases, best way is to make
use of binary trees.
Introduction and Definition
Definition: A binary tree is a tree data structure in
which each parent node can have at most two
children. Each node of a binary tree consists of
three items:
• data item
• address of left child
• address of right child
1. Root:- A root is a node without a
parent. In the above image, 50 is the root
node.
2. Siblings:- Siblings mean that nodes
which have the same parent node. In the
above image, 17 and 72 are siblings
because they have 50 in common.
3. Internal Node:- Internal Node means
that a node which has at least a single
child. In the above image, 17, 72, 12,
23, 54 are internal nodes.
4. External Node:- External Node means
that a node which has no children. It is
also known as leaf. In the above image,
67 and 76 are external nodes.
5. Ancestors:- Ancestors include the
parent, grandparent and so on of a node.
In the above image, the ancestors of 23 are
17 and 50.
6. Descendants:- Descendants are the
opposite of ancestors, It includes the child,
grandchild and so on of a node. In the
above image, the descendants of 17 are
12,23,19,9,14.
7. Edge:- An edge means a connection
between one node to another node.
8. Path:- Path is a combination of nodes
and edges connected with each other. In
the above image, 50 to 19 is a path.
9. Depth:- You can calculate depth by the number of edges from node to the root
of the tree.
10. Height:- Height is the maximum depth of a node.
11. Level:- Level of a node is equal to depth of the node+1.
Types of Binary Trees
1. Full Binary Tree
A full Binary tree is a special type of
binary tree in which every parent
node/internal node has either two or
no children. We can also say a full
binary tree is a binary tree in which
all nodes except leaf nodes have two
children.
2. Perfect Binary Tree
A perfect binary tree is a type of
binary tree in which every internal
node has exactly two child nodes and
all the leaf nodes are at the same
level.
3. Complete Binary Tree
A complete binary tree is just like a full binary tree, but with two
major differences
1. Every level must be completely filled
2. All the leaf elements must lean towards the left.
3. The last leaf element might not have a right sibling i.e. a
complete binary tree doesn't have to be a full binary tree.
Properties of Complete Binary Tree
Max Nodes Min Nodes
Binary Tree 2h+1
- 1 h+1
Full Binary Tree 2h+1
- 1 2h+1
Complete Binary Tree 2h+1
- 1 2h
Max Height Min Height
Binary Tree log2(n+1) - 1 n-1
Full Binary Tree log2(n+1) - 1 (n-1)/2
Complete Binary Tree log2(n+1) - 1 logn
BINARY TREE REPRESENTATION
• The storage representation of binary trees can be classified as
1. Array representation
2. Linked representation.
Array representation
• A tree can be represented using an
array, which is called sequential
representation.
• The nodes are numbered from 1 to
n, and one dimensional array can
be used to store the nodes.
• Position 0 of this array is left empty
and the node numbered i is
mapped to position i of the array
Implicit Array Representation of Binary Trees
0 1 2 3 4 5 6 7 8
A B C D E F G H I
A
C
B
E
D F G
I
H
Case 1:
If a node is in the ith index:
Left child would be at ((2*i)+1)
Right child would be at ((2*i)+2)
Parent would be at floor((i-1)/2)
1 2 3 4 5 6 7 8 9
A B C D E F G H I
Case 2:
If a node is in the ith index:
Left child would be at (2*i)
Right child would be at ((2*i)+1)
Parent would be floor(i/2)
Implicit Array Representation of Binary Trees
0 1 2 3 4 5 6 7 8 9 10
A B C D E F G - - H I
A
C
B
E
D F G
Case 1:
If a node is in the ith index:
Left child would be at ((2*i)+1)
Right child would be at ((2*i)+2)
Parent would be at floor((i-1)/2)
Case 2:
If a node is in the ith index:
Left child would be at (2*i)
Right child would be at ((2*i)+1)
Parent would be floor(i/2)
H I
1 2 3 4 5 6 7 8 9 10 11
A B C D E F G - - H I
Implicit Array Representation of Binary Trees
0 1 2 3 4 5 6 7
A B C D E F G H
A
C
B
E
D F G
H
Case 1:
If a node is in the ith index:
Left child would be at ((2*i)+1)
Right child would be at ((2*i)+2)
Parent would be at floor((i-1)/2)
1 2 3 4 5 6 7 8
A B C D E F G H
Case 2:
If a node is in the ith index:
Left child would be at (2*i)
Right child would be at ((2*i)+1)
Parent would be floor(i/2)
Implicit Array Representation of Binary Trees
0 1 2 3 4 5 6
A - B - - - C
A
B
C
Case 1:
If a node is in the ith index:
Left child would be at ((2*i)+1)
Right child would be at ((2*i)+2)
Parent would be at floor((i-1)/2)
1 2 3 4 5 6 7
A - B - - - C
Case 2:
If a node is in the ith index:
Left child would be at (2*i)
Right child would be at ((2*i)+1)
Parent would be floor(i/2)
Implicit Array Representation of Binary Trees
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
A - B - - - C - - - - - - - D
A
B
C
Case 1:
If a node is in the ith index:
Left child would be at ((2*i)+1)
Right child would be at ((2*i)+2)
Parent would be at floor((i-1)/2)
Case 2:
If a node is in the ith index:
Left child would be at (2*i)
Right child would be at ((2*i)+1)
Parent would be floor(i/2)
D
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
A - B - - - C - - - - - - - D
Binary Tree Implementation
250 3 0 0 7 300
0 -1 0 0 10 0
200 4 40
0
100
root
100
200 400
250 300
#include<stdio.h>
struct node
{
int data;
struct node *left, *right;
}
void main()
{
struct node *root;
root=0;
root = create();
}
Binary Tree Implementation
250 3 0 0 7 300
0 -1 0 0 10 0
200 4 40
0
100
root
100
200 400
250 300
struct node *create()
{
struct node *newnode;
int data;
printf("Press 0 to exit");
printf("nPress 1 for new node");
printf("Enter your choice : ");
scanf("%d", &choice);
if(choice==0)
{
return 0;
}
else
{
newnode = (struct node *)malloc(sizeof(struct node));
printf("Enter the data:");
scanf("%d", &newnode->data);
printf("Enter the left child of %d", data);
newnode->left = create();
printf("Enter the right child of %d", data);
newnode->right = create();
return newnode;
} }
Binary Tree Implementation
struct node *create()
{
struct node *newnode;
int data;
printf("Press 0 to exit");
printf("nPress 1 for new node");
printf("Enter your choice : ");
scanf("%d", &choice);
if(choice==0)
{
return 0;
}
else
{
newnode = (struct node *)malloc
(sizeof(struct node));
printf("Enter the data:");
scanf("%d", &newnode->data);
printf("Enter the left child of %d", data);
newnode->left = create();
printf("Enter the right child of %d", data);
newnode->right = create();
return newnode;
}
}
BINARY TREE TRAVERSALS
• Visiting each node in a tree exactly once is called tree
traversal
• The different methods of traversing a binary tree are:
1. Preorder
2. Inorder
3. Postorder
1. Inorder
• Inorder traversal calls for moving down the
tree toward the left until you cannot go further.
Then visit the node, move one node to the
right and continue. If no move can be done,
then go back one more node.
• Let ptr is the pointer which contains the
location of the node N currently being scanned.
• L(N) denotes the leftchild of node N and R(N) is
the right child of node N
Recursion function:
• The inorder traversal of a binary tree can be recursively defined as
– Traverse the left subtree in inorder.
– Visit the root.
– Traverse the right subtree in inorder.
void inorder(treepointer ptr)
{ if (ptr)
{ inorder (ptr→leftchild);
printf (“%d”,ptr→data);
inorder (ptr→rightchild);
}
}
2. Preorder
• Preorder is the procedure of visiting a node, traverse left and
continue.
• When you cannot continue, move right and begin again or
move back until you can move right and resume.
• Recursion function:
The Preorder traversal of a binary tree can be recursively defined as
– Visit the root
– Traverse the left subtree in preorder.
– Traverse the right subtree in preorder
void preorder (treepointer ptr)
{ if (ptr)
{ printf (“%d”,ptr→data);
preorder (ptr→leftchild);
preorder (ptr→rightchild);
}
}
3. Postorder
• Postorder traversal calls for moving down the tree towards
the left until you can go no further.
• Then move to the right node and then visit the node and
continue.
• Recursion function:
The Postorder traversal of a binary tree can be recursively defined as
 Traverse the left subtree in postorder.
 Traverse the right subtree in postorder.
 Visit the root
void postorder(treepointerptr)
{ if (ptr)
{ postorder (ptr→leftchild);
postorder (ptr→rightchild);
printf (“%d”,ptr→data);
}
}
EXAMPLES
The preorder enumeration for the tree is A B D C E G F H I.
The postorder enumeration for the tree is D B G E H I F C A.
The inorder enumeration for the tree is B D A G E C H F I.
PREORDER TRAVERSAL ALGORITHM USING STACKS
TRAVERSAL ALGORITHM USING STACKS
Processed Element
INORDER TRAVERSAL ALGORITHM USING STACKS
2
TRAVERSAL ALGORITHM USING STACKS
Processed Element
TRAVERSAL ALGORITHM USING STACKS
TRAVERSAL ALGORITHM USING STACKS
Processed Element
-
-
PTR=-500
PTR=-PTR
=-(-500)
=5000
Binary Tree Traversals
• Arithmetic Expression using binary tree
– inorder traversal (infix expression)
A / B * C * D + E
– preorder traversal (prefix expression)
+ * * / A B C D E
– postorder traversal
(postfix expression)
A B / C * D * E +
– level order traversal
+ * E * D / C A B
Binary Tree Traversals (3/9)
• Inorder traversal (LVR) (recursive version)
L
V
R
ptr
output
:
A / B * C * D + E
Binary Tree Traversals (4/9)
• Preorder traversal (VLR) (recursive version)
V
L
R
output
:
A
/ B
* C
* D
+ E
Binary Tree Traversals (5/9)
• Postorder traversal (LRV) (recursive version)
L
R
V
output
:
A /
B *
C * D +
E
Binary Tree Traversals (6/9)
• Iterative inorder traversal
– we use a stack to simulate recursion
L
V
R
1
+
node
output
:
A /B *C *D + E
2
*
3
*
4
/
5
A
8
B
11
C
14
D
17
E
Threaded Binary Trees
• Threads
– Do you find any drawback of the above tree?
– Too many null pointers in current representation of binary trees
n: number of nodes
number of non-null links: n-1
total links: 2n
null links: 2n-(n-1) = n+1
– Solution: replace these null pointers with some useful “threads”
Binary Tree
Threaded Binary Trees
• Rules for constructing the threads
– If ptr->left_child is null,
replace it with a pointer to the node that would be visited before ptr in an
inorder traversal that is Inorder Predecessor.
– If ptr->right_child is null,
replace it with a pointer to the node that would be visited after ptr in an
inorder traversal that is Inorder Successor.
Binary Tree
Inorder Traversal- D,B,E,G,A,C,F
Threaded Binary Trees
• Two additional fields of the node structure, left-thread and right-thread
– If ptr->left-thread=TRUE,
then ptr->left-child contains a thread;
– Otherwise it contains a pointer to the left child.
– Similarly for the right-thread
Threaded Binary Trees
• A Threaded Binary Tree
A
C
G
I
D
H
F
dangling
dangling
H D I B E A F C G
inorder traversal:
E t
t
B f
f
t: true  thread
f: false  child
root
Threaded Binary Trees
• If we don’t want the left pointer of H and the right pointer of G to be dangling
pointers, we may create root node and assign them pointing to the root node
Threaded Binary Trees
Inorder traversal of a threaded binary tree
• By using of threads we can perform an inorder traversal without making use of
a stack (simplifying the task)
• Now, we can follow the thread of any node, ptr, to the “next” node of inorder
traversal
1. If ptr->right_thread = TRUE, the inorder successor of ptr is ptr-
>right_child by definition of the threads
2. Otherwise we obtain the inorder successor of ptr by following a path of left-
child links from the right-child of ptr until we reach a node with left_thread =
TRUE
Threaded Binary Trees
• Finding the inorder successor (next node) of a node
threaded_pointer insucc(threaded_pointer tree){
threaded_pointer temp;
temp = tree->right_child;
if (!tree->right_thread)
while (!temp->left_thread)
temp = temp->left_child;
return temp;
}
Inorder
tree
temp
Threaded Binary Trees
• Inorder traversal of a threaded binary tree
void tinorder(threaded_pointer tree){
/* traverse the threaded binary tree inorder */
threaded_pointer temp = tree;
for (;;) {
temp = insucc(temp);
if (temp==tree)
break;
printf(“%3c”,temp->data);
}
}
Time Complexity: O(n)
tree
output
:
F C G
H D I B E A
Threaded Binary Trees
Inserting A Node Into A Threaded Binary Tree
Insert child as the right child of node parent
1. change parent->right_thread to FALSE
2. set child->left_thread and child->right_thread to TRUE
3. set child->left_child to point to parent
4. set child->right_child to parent->right_child
5. change parent->right_child to point to child
Right insertion in a threaded binary tree
void insertRight(threadedPointer Sf threadedPointer r)
{ /* insert r as the right child of s */
threadedpointer temp;
r→rightChild = parent→rightChild;
r→rightThread = parent→rightThread;
r→leftChild = parent;
r→leftThread = TRUE;
s→rightChild = child;
s→rightThread = FALSE;
if (!r→rightThread)
{
temp = insucc(r);
temp→leftChild = r;
}
}
Right insertion in a threaded binary tree
void insertRight(threadedPointer Sf threadedPointer r)
{ /* insert r as the right child of s */
threadedpointer temp;
r→rightChild = parent→rightChild;
r→rightThread = parent→rightThread;
r→leftChild = parent;
r→leftThread = TRUE;
s→rightChild = child;
s→rightThread = FALSE;
if (!r→rightThread)
{
temp = insucc(r);
temp→leftChild = r;
}
}
Binary Search Trees
Definition of binary search tree:
– Every element has a unique key
– The keys in a nonempty left subtree are smaller than the key in the root
of subtree
– The keys in a nonempty right subtree are larger than the key in the root
of subtree
– The left and right subtrees are also binary search trees
Binary Search Trees
Example: (b) and (c) are binary search trees
medium
larger
smaller
Difference between BT and BST
•A binary tree is simply a tree in which each node can have at most two
children.
•A binary search tree is a binary tree in which the nodes are assigned
values, with the following restrictions :
1. No duplicate values.
2. The left subtree of a node can only have values less than the node
3. The right subtree of a node can only have values greater than the
node and recursively defined
4. The left subtree of a node is a binary search tree.
5. The right subtree of a node is a binary search tree.
Four basic BST operations
1
Traversal
2
Search
3
Insertion
4
Deletion
BST Operations
BST Traversal
PreorderTraversal
23 18 12 20 44 35 52
Root Left Right
PostorderTraversal
12 20 18 35 52 44 23
Left Right Root
InorderTraversal
12 18 20 23 35 44 52
Produces a sequenced list
Left Root Right
44
32 65
88
28
17
80
76
97
82
54
29
Search(25) Search(76)
Binary Search Trees
• Search:
S
e
a
r
c
h
A
l
g
o
ri
t
h
m
Searching in BST
• Searching a
binary search
tree
O(h)
BST Insertion Algorithm
Inserting into a binary search tree
An empty tree
Deletion from BST
• Deletion from a binary search tree
– Three cases should be considered
– case 1. leaf  delete
– case 2. one child  delete and change
the pointer to this child
– case 3. two child  either the
smallest element in the right subtree
or the largest element in the left
subtree
BST Deletion Algorithm
BST Deletion Algorithm
Binary Search Trees
• Height of a binary search tree
– The height of a binary search tree with n elements can become as
large as n.
– It can be shown that when insertions and deletions are made at
random, the height of the binary search tree is O(log2n) on the
average.
– Search trees with a worst-case height of O(log2n) are called balance
search trees
Binary Search Trees
• Time Complexity
– Searching, insertion, removal
• O(h), where h is the height of the tree
– Worst case - skewed binary tree
• O(n), where n is the # of internal nodes
• Prevent worst case
– rebalancing scheme
– AVL, 2-3, and Red-black tree
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
• Inorder traversal of expression tree produces infix
version of given postfix expression (same with
postorder traversal it gives postfix expression)
Binary Trees.pptx module 122img 787554yau
Evaluating an expression tree
Let n be node in expression tree
evaluate(n)
If n is not null then
If n.value is operand then
Return n.value
else
the operator is stored at n.value
A = evaluate(n.left)
B = evaluate(n.right)
// calculate applies operator 't.value'
// on A and B, and returns value
Return calculate(A, B, n.value)
Constructing a 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.

More Related Content

PPTX
Tree
PDF
Chapter 5_Trees.pdf
PPT
Unit iii(dsc++)
PPTX
Unit 6 tree
PPT
Final tree.ppt tells about tree presentation
PPT
PDF
Chapter 7 - Binary Search Tree in the context of DSA.pdf
PDF
Dsc++ unit 3 notes
Tree
Chapter 5_Trees.pdf
Unit iii(dsc++)
Unit 6 tree
Final tree.ppt tells about tree presentation
Chapter 7 - Binary Search Tree in the context of DSA.pdf
Dsc++ unit 3 notes

Similar to Binary Trees.pptx module 122img 787554yau (20)

PPT
Data Structure And Algorithms for Computer Science
PPT
9. TREE Data Structure Non Linear Data Structure
PPTX
VCE Unit 05.pptx
PPT
358 33 powerpoint-slides_10-trees_chapter-10
PPTX
PPTX
Tree structure and its definitions with an example
DOCX
data structures Unit 3 notes.docxdata structures Unit 3 notes.docx
PPTX
Trees in Data Structure
PPT
Lecture 5 tree.pptx
PPT
UNIT-4 TREES.ppt
PPTX
Tree.pptx
PDF
Trees in Data Structure
PPTX
Data Structure of computer science and technology
PDF
AD3251-Data Structures Design-Notes-Tree.pdf
PPTX
UNIT III Non Linear Data Structures - Trees.pptx
PPTX
UNIT 2 TREES & GRAPH COMPLETE NOTES OF DATA STRUCTURE
PPT
Binary search Tree and avl tree , treee.ppt
PPTX
NON-LINEAR DATA STRUCTURE-TREES.pptx
PDF
7 chapter4 trees_binary
PPTX
UNIT III Non Linear Data Structures - Trees.pptx
Data Structure And Algorithms for Computer Science
9. TREE Data Structure Non Linear Data Structure
VCE Unit 05.pptx
358 33 powerpoint-slides_10-trees_chapter-10
Tree structure and its definitions with an example
data structures Unit 3 notes.docxdata structures Unit 3 notes.docx
Trees in Data Structure
Lecture 5 tree.pptx
UNIT-4 TREES.ppt
Tree.pptx
Trees in Data Structure
Data Structure of computer science and technology
AD3251-Data Structures Design-Notes-Tree.pdf
UNIT III Non Linear Data Structures - Trees.pptx
UNIT 2 TREES & GRAPH COMPLETE NOTES OF DATA STRUCTURE
Binary search Tree and avl tree , treee.ppt
NON-LINEAR DATA STRUCTURE-TREES.pptx
7 chapter4 trees_binary
UNIT III Non Linear Data Structures - Trees.pptx
Ad

Recently uploaded (20)

PPTX
additive manufacturing of ss316l using mig welding
PPTX
Construction Project Organization Group 2.pptx
PDF
Model Code of Practice - Construction Work - 21102022 .pdf
PPT
CRASH COURSE IN ALTERNATIVE PLUMBING CLASS
PDF
The CXO Playbook 2025 – Future-Ready Strategies for C-Suite Leaders Cerebrai...
PDF
Operating System & Kernel Study Guide-1 - converted.pdf
PPTX
UNIT-1 - COAL BASED THERMAL POWER PLANTS
PPTX
CYBER-CRIMES AND SECURITY A guide to understanding
PDF
R24 SURVEYING LAB MANUAL for civil enggi
PDF
PRIZ Academy - 9 Windows Thinking Where to Invest Today to Win Tomorrow.pdf
PDF
Mohammad Mahdi Farshadian CV - Prospective PhD Student 2026
PPTX
KTU 2019 -S7-MCN 401 MODULE 2-VINAY.pptx
PPTX
Geodesy 1.pptx...............................................
PPTX
Foundation to blockchain - A guide to Blockchain Tech
PPT
Mechanical Engineering MATERIALS Selection
PDF
July 2025 - Top 10 Read Articles in International Journal of Software Enginee...
DOCX
573137875-Attendance-Management-System-original
PDF
Automation-in-Manufacturing-Chapter-Introduction.pdf
PPTX
Welding lecture in detail for understanding
PPTX
bas. eng. economics group 4 presentation 1.pptx
additive manufacturing of ss316l using mig welding
Construction Project Organization Group 2.pptx
Model Code of Practice - Construction Work - 21102022 .pdf
CRASH COURSE IN ALTERNATIVE PLUMBING CLASS
The CXO Playbook 2025 – Future-Ready Strategies for C-Suite Leaders Cerebrai...
Operating System & Kernel Study Guide-1 - converted.pdf
UNIT-1 - COAL BASED THERMAL POWER PLANTS
CYBER-CRIMES AND SECURITY A guide to understanding
R24 SURVEYING LAB MANUAL for civil enggi
PRIZ Academy - 9 Windows Thinking Where to Invest Today to Win Tomorrow.pdf
Mohammad Mahdi Farshadian CV - Prospective PhD Student 2026
KTU 2019 -S7-MCN 401 MODULE 2-VINAY.pptx
Geodesy 1.pptx...............................................
Foundation to blockchain - A guide to Blockchain Tech
Mechanical Engineering MATERIALS Selection
July 2025 - Top 10 Read Articles in International Journal of Software Enginee...
573137875-Attendance-Management-System-original
Automation-in-Manufacturing-Chapter-Introduction.pdf
Welding lecture in detail for understanding
bas. eng. economics group 4 presentation 1.pptx
Ad

Binary Trees.pptx module 122img 787554yau

  • 2. Contents Binary Trees: Introduction and definition, Node Representation of Binary Trees, Internal and External Nodes, Implicit Array Representation of Binary Trees, Primitive operations on Binary Tree, Threaded binary tree, Binary search tree and its primitive operations, General Expressions as Trees, evaluating an expression tree, constructing a Tree.
  • 3. DEFINITION • A tree is a finite set of one or more nodes such that – There is a specially designated node called root. – The remaining nodes are partitioned into n >= 0 disjoint set T1,…,Tn, where each of these sets is a tree. – T1,…,Tn are called the subtrees of the root
  • 4. Introduction Trees: Unlike Arrays, Linked Lists, Stack and queues, which are linear data structures, trees are hierarchical data structures. Tree Vocabulary: The topmost node is called root of the tree. The elements that are directly under an element are called its children. The element directly above something is called its parent. For example, ‘a’ is a child of ‘f’, and ‘f’ is the parent of ‘a’. Finally, elements with no children are called leaves.
  • 5. Why Trees? 1. One reason to use trees might be to store information that naturally forms a hierarchy. For example, the file system on a computer 2. Trees (with some ordering e.g., BST) provide moderate access/search (quicker than Linked List and slower than arrays). 3. Trees provide moderate insertion/deletion (quicker than Arrays and slower than Unordered Linked Lists). 4. Like Linked Lists and unlike Arrays, Trees don’t have an upper limit on
  • 6. Need for binary trees: • In C, Binary trees have some exciting and useful applications which can be implemented. • With the help of a binary search tree, an element can be found in a huge set because it is fast and efficient. • Using binary trees, implementation of heapsort is easy. • To store information in databases, best way is to make use of binary trees.
  • 7. Introduction and Definition Definition: A binary tree is a tree data structure in which each parent node can have at most two children. Each node of a binary tree consists of three items: • data item • address of left child • address of right child
  • 8. 1. Root:- A root is a node without a parent. In the above image, 50 is the root node. 2. Siblings:- Siblings mean that nodes which have the same parent node. In the above image, 17 and 72 are siblings because they have 50 in common. 3. Internal Node:- Internal Node means that a node which has at least a single child. In the above image, 17, 72, 12, 23, 54 are internal nodes. 4. External Node:- External Node means that a node which has no children. It is also known as leaf. In the above image, 67 and 76 are external nodes.
  • 9. 5. Ancestors:- Ancestors include the parent, grandparent and so on of a node. In the above image, the ancestors of 23 are 17 and 50. 6. Descendants:- Descendants are the opposite of ancestors, It includes the child, grandchild and so on of a node. In the above image, the descendants of 17 are 12,23,19,9,14. 7. Edge:- An edge means a connection between one node to another node. 8. Path:- Path is a combination of nodes and edges connected with each other. In the above image, 50 to 19 is a path. 9. Depth:- You can calculate depth by the number of edges from node to the root of the tree. 10. Height:- Height is the maximum depth of a node. 11. Level:- Level of a node is equal to depth of the node+1.
  • 10. Types of Binary Trees 1. Full Binary Tree A full Binary tree is a special type of binary tree in which every parent node/internal node has either two or no children. We can also say a full binary tree is a binary tree in which all nodes except leaf nodes have two children. 2. Perfect Binary Tree A perfect binary tree is a type of binary tree in which every internal node has exactly two child nodes and all the leaf nodes are at the same level.
  • 11. 3. Complete Binary Tree A complete binary tree is just like a full binary tree, but with two major differences 1. Every level must be completely filled 2. All the leaf elements must lean towards the left. 3. The last leaf element might not have a right sibling i.e. a complete binary tree doesn't have to be a full binary tree.
  • 12. Properties of Complete Binary Tree Max Nodes Min Nodes Binary Tree 2h+1 - 1 h+1 Full Binary Tree 2h+1 - 1 2h+1 Complete Binary Tree 2h+1 - 1 2h Max Height Min Height Binary Tree log2(n+1) - 1 n-1 Full Binary Tree log2(n+1) - 1 (n-1)/2 Complete Binary Tree log2(n+1) - 1 logn
  • 13. BINARY TREE REPRESENTATION • The storage representation of binary trees can be classified as 1. Array representation 2. Linked representation.
  • 14. Array representation • A tree can be represented using an array, which is called sequential representation. • The nodes are numbered from 1 to n, and one dimensional array can be used to store the nodes. • Position 0 of this array is left empty and the node numbered i is mapped to position i of the array
  • 15. Implicit Array Representation of Binary Trees 0 1 2 3 4 5 6 7 8 A B C D E F G H I A C B E D F G I H Case 1: If a node is in the ith index: Left child would be at ((2*i)+1) Right child would be at ((2*i)+2) Parent would be at floor((i-1)/2) 1 2 3 4 5 6 7 8 9 A B C D E F G H I Case 2: If a node is in the ith index: Left child would be at (2*i) Right child would be at ((2*i)+1) Parent would be floor(i/2)
  • 16. Implicit Array Representation of Binary Trees 0 1 2 3 4 5 6 7 8 9 10 A B C D E F G - - H I A C B E D F G Case 1: If a node is in the ith index: Left child would be at ((2*i)+1) Right child would be at ((2*i)+2) Parent would be at floor((i-1)/2) Case 2: If a node is in the ith index: Left child would be at (2*i) Right child would be at ((2*i)+1) Parent would be floor(i/2) H I 1 2 3 4 5 6 7 8 9 10 11 A B C D E F G - - H I
  • 17. Implicit Array Representation of Binary Trees 0 1 2 3 4 5 6 7 A B C D E F G H A C B E D F G H Case 1: If a node is in the ith index: Left child would be at ((2*i)+1) Right child would be at ((2*i)+2) Parent would be at floor((i-1)/2) 1 2 3 4 5 6 7 8 A B C D E F G H Case 2: If a node is in the ith index: Left child would be at (2*i) Right child would be at ((2*i)+1) Parent would be floor(i/2)
  • 18. Implicit Array Representation of Binary Trees 0 1 2 3 4 5 6 A - B - - - C A B C Case 1: If a node is in the ith index: Left child would be at ((2*i)+1) Right child would be at ((2*i)+2) Parent would be at floor((i-1)/2) 1 2 3 4 5 6 7 A - B - - - C Case 2: If a node is in the ith index: Left child would be at (2*i) Right child would be at ((2*i)+1) Parent would be floor(i/2)
  • 19. Implicit Array Representation of Binary Trees 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 A - B - - - C - - - - - - - D A B C Case 1: If a node is in the ith index: Left child would be at ((2*i)+1) Right child would be at ((2*i)+2) Parent would be at floor((i-1)/2) Case 2: If a node is in the ith index: Left child would be at (2*i) Right child would be at ((2*i)+1) Parent would be floor(i/2) D 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 A - B - - - C - - - - - - - D
  • 20. Binary Tree Implementation 250 3 0 0 7 300 0 -1 0 0 10 0 200 4 40 0 100 root 100 200 400 250 300 #include<stdio.h> struct node { int data; struct node *left, *right; } void main() { struct node *root; root=0; root = create(); }
  • 21. Binary Tree Implementation 250 3 0 0 7 300 0 -1 0 0 10 0 200 4 40 0 100 root 100 200 400 250 300 struct node *create() { struct node *newnode; int data; printf("Press 0 to exit"); printf("nPress 1 for new node"); printf("Enter your choice : "); scanf("%d", &choice); if(choice==0) { return 0; } else { newnode = (struct node *)malloc(sizeof(struct node)); printf("Enter the data:"); scanf("%d", &newnode->data); printf("Enter the left child of %d", data); newnode->left = create(); printf("Enter the right child of %d", data); newnode->right = create(); return newnode; } }
  • 22. Binary Tree Implementation struct node *create() { struct node *newnode; int data; printf("Press 0 to exit"); printf("nPress 1 for new node"); printf("Enter your choice : "); scanf("%d", &choice); if(choice==0) { return 0; } else { newnode = (struct node *)malloc (sizeof(struct node)); printf("Enter the data:"); scanf("%d", &newnode->data); printf("Enter the left child of %d", data); newnode->left = create(); printf("Enter the right child of %d", data); newnode->right = create(); return newnode; } }
  • 23. BINARY TREE TRAVERSALS • Visiting each node in a tree exactly once is called tree traversal • The different methods of traversing a binary tree are: 1. Preorder 2. Inorder 3. Postorder
  • 24. 1. Inorder • Inorder traversal calls for moving down the tree toward the left until you cannot go further. Then visit the node, move one node to the right and continue. If no move can be done, then go back one more node. • Let ptr is the pointer which contains the location of the node N currently being scanned. • L(N) denotes the leftchild of node N and R(N) is the right child of node N
  • 25. Recursion function: • The inorder traversal of a binary tree can be recursively defined as – Traverse the left subtree in inorder. – Visit the root. – Traverse the right subtree in inorder. void inorder(treepointer ptr) { if (ptr) { inorder (ptr→leftchild); printf (“%d”,ptr→data); inorder (ptr→rightchild); } }
  • 26. 2. Preorder • Preorder is the procedure of visiting a node, traverse left and continue. • When you cannot continue, move right and begin again or move back until you can move right and resume. • Recursion function: The Preorder traversal of a binary tree can be recursively defined as – Visit the root – Traverse the left subtree in preorder. – Traverse the right subtree in preorder void preorder (treepointer ptr) { if (ptr) { printf (“%d”,ptr→data); preorder (ptr→leftchild); preorder (ptr→rightchild); } }
  • 27. 3. Postorder • Postorder traversal calls for moving down the tree towards the left until you can go no further. • Then move to the right node and then visit the node and continue. • Recursion function: The Postorder traversal of a binary tree can be recursively defined as  Traverse the left subtree in postorder.  Traverse the right subtree in postorder.  Visit the root void postorder(treepointerptr) { if (ptr) { postorder (ptr→leftchild); postorder (ptr→rightchild); printf (“%d”,ptr→data); } }
  • 28. EXAMPLES The preorder enumeration for the tree is A B D C E G F H I. The postorder enumeration for the tree is D B G E H I F C A. The inorder enumeration for the tree is B D A G E C H F I.
  • 30. TRAVERSAL ALGORITHM USING STACKS Processed Element
  • 31. INORDER TRAVERSAL ALGORITHM USING STACKS 2
  • 32. TRAVERSAL ALGORITHM USING STACKS Processed Element
  • 34. TRAVERSAL ALGORITHM USING STACKS Processed Element - - PTR=-500 PTR=-PTR =-(-500) =5000
  • 35. Binary Tree Traversals • Arithmetic Expression using binary tree – inorder traversal (infix expression) A / B * C * D + E – preorder traversal (prefix expression) + * * / A B C D E – postorder traversal (postfix expression) A B / C * D * E + – level order traversal + * E * D / C A B
  • 36. Binary Tree Traversals (3/9) • Inorder traversal (LVR) (recursive version) L V R ptr output : A / B * C * D + E
  • 37. Binary Tree Traversals (4/9) • Preorder traversal (VLR) (recursive version) V L R output : A / B * C * D + E
  • 38. Binary Tree Traversals (5/9) • Postorder traversal (LRV) (recursive version) L R V output : A / B * C * D + E
  • 39. Binary Tree Traversals (6/9) • Iterative inorder traversal – we use a stack to simulate recursion L V R 1 + node output : A /B *C *D + E 2 * 3 * 4 / 5 A 8 B 11 C 14 D 17 E
  • 40. Threaded Binary Trees • Threads – Do you find any drawback of the above tree? – Too many null pointers in current representation of binary trees n: number of nodes number of non-null links: n-1 total links: 2n null links: 2n-(n-1) = n+1 – Solution: replace these null pointers with some useful “threads”
  • 42. Threaded Binary Trees • Rules for constructing the threads – If ptr->left_child is null, replace it with a pointer to the node that would be visited before ptr in an inorder traversal that is Inorder Predecessor. – If ptr->right_child is null, replace it with a pointer to the node that would be visited after ptr in an inorder traversal that is Inorder Successor.
  • 44. Threaded Binary Trees • Two additional fields of the node structure, left-thread and right-thread – If ptr->left-thread=TRUE, then ptr->left-child contains a thread; – Otherwise it contains a pointer to the left child. – Similarly for the right-thread
  • 45. Threaded Binary Trees • A Threaded Binary Tree A C G I D H F dangling dangling H D I B E A F C G inorder traversal: E t t B f f t: true  thread f: false  child root
  • 46. Threaded Binary Trees • If we don’t want the left pointer of H and the right pointer of G to be dangling pointers, we may create root node and assign them pointing to the root node
  • 47. Threaded Binary Trees Inorder traversal of a threaded binary tree • By using of threads we can perform an inorder traversal without making use of a stack (simplifying the task) • Now, we can follow the thread of any node, ptr, to the “next” node of inorder traversal 1. If ptr->right_thread = TRUE, the inorder successor of ptr is ptr- >right_child by definition of the threads 2. Otherwise we obtain the inorder successor of ptr by following a path of left- child links from the right-child of ptr until we reach a node with left_thread = TRUE
  • 48. Threaded Binary Trees • Finding the inorder successor (next node) of a node threaded_pointer insucc(threaded_pointer tree){ threaded_pointer temp; temp = tree->right_child; if (!tree->right_thread) while (!temp->left_thread) temp = temp->left_child; return temp; } Inorder tree temp
  • 49. Threaded Binary Trees • Inorder traversal of a threaded binary tree void tinorder(threaded_pointer tree){ /* traverse the threaded binary tree inorder */ threaded_pointer temp = tree; for (;;) { temp = insucc(temp); if (temp==tree) break; printf(“%3c”,temp->data); } } Time Complexity: O(n) tree output : F C G H D I B E A
  • 50. Threaded Binary Trees Inserting A Node Into A Threaded Binary Tree Insert child as the right child of node parent 1. change parent->right_thread to FALSE 2. set child->left_thread and child->right_thread to TRUE 3. set child->left_child to point to parent 4. set child->right_child to parent->right_child 5. change parent->right_child to point to child
  • 51. Right insertion in a threaded binary tree void insertRight(threadedPointer Sf threadedPointer r) { /* insert r as the right child of s */ threadedpointer temp; r→rightChild = parent→rightChild; r→rightThread = parent→rightThread; r→leftChild = parent; r→leftThread = TRUE; s→rightChild = child; s→rightThread = FALSE; if (!r→rightThread) { temp = insucc(r); temp→leftChild = r; } }
  • 52. Right insertion in a threaded binary tree void insertRight(threadedPointer Sf threadedPointer r) { /* insert r as the right child of s */ threadedpointer temp; r→rightChild = parent→rightChild; r→rightThread = parent→rightThread; r→leftChild = parent; r→leftThread = TRUE; s→rightChild = child; s→rightThread = FALSE; if (!r→rightThread) { temp = insucc(r); temp→leftChild = r; } }
  • 53. Binary Search Trees Definition of binary search tree: – Every element has a unique key – The keys in a nonempty left subtree are smaller than the key in the root of subtree – The keys in a nonempty right subtree are larger than the key in the root of subtree – The left and right subtrees are also binary search trees
  • 54. Binary Search Trees Example: (b) and (c) are binary search trees medium larger smaller
  • 55. Difference between BT and BST •A binary tree is simply a tree in which each node can have at most two children. •A binary search tree is a binary tree in which the nodes are assigned values, with the following restrictions : 1. No duplicate values. 2. The left subtree of a node can only have values less than the node 3. The right subtree of a node can only have values greater than the node and recursively defined 4. The left subtree of a node is a binary search tree. 5. The right subtree of a node is a binary search tree.
  • 56. Four basic BST operations 1 Traversal 2 Search 3 Insertion 4 Deletion BST Operations
  • 58. PreorderTraversal 23 18 12 20 44 35 52 Root Left Right
  • 59. PostorderTraversal 12 20 18 35 52 44 23 Left Right Root
  • 60. InorderTraversal 12 18 20 23 35 44 52 Produces a sequenced list Left Root Right
  • 63. Searching in BST • Searching a binary search tree O(h)
  • 65. Inserting into a binary search tree An empty tree
  • 66. Deletion from BST • Deletion from a binary search tree – Three cases should be considered – case 1. leaf  delete – case 2. one child  delete and change the pointer to this child – case 3. two child  either the smallest element in the right subtree or the largest element in the left subtree
  • 69. Binary Search Trees • Height of a binary search tree – The height of a binary search tree with n elements can become as large as n. – It can be shown that when insertions and deletions are made at random, the height of the binary search tree is O(log2n) on the average. – Search trees with a worst-case height of O(log2n) are called balance search trees
  • 70. Binary Search Trees • Time Complexity – Searching, insertion, removal • O(h), where h is the height of the tree – Worst case - skewed binary tree • O(n), where n is the # of internal nodes • Prevent worst case – rebalancing scheme – AVL, 2-3, and Red-black tree
  • 71. 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 • Inorder traversal of expression tree produces infix version of given postfix expression (same with postorder traversal it gives postfix expression)
  • 73. Evaluating an expression tree Let n be node in expression tree evaluate(n) If n is not null then If n.value is operand then Return n.value else the operator is stored at n.value A = evaluate(n.left) B = evaluate(n.right) // calculate applies operator 't.value' // on A and B, and returns value Return calculate(A, B, n.value)
  • 74. Constructing a 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.