SlideShare a Scribd company logo
Binary Tree
Prepared by: Afaq Mansoor Khan
BSSE III- Group A
Session 2017-21
IMSciences, Peshawar.
Last Lecture Summary
• Introduction to Queue Data Structure
• Types of Queue Data Structures
• Circular QUEUE and its Operations
• Double Ended QUEUE and its operations
Objectives Overview
• Introduction to Binary Tree
• Operations in Binary tree
• Recursive and Non Recursive Traversal of Binary/Binary
Search Tree
• In-Order Traversal
• Pre-Order Traversal
• Post-Order Traversal
• Insertion of New Node in BST
• Deletion of a Node from BST
• Searching in a Binary Search Tree
Introduction to Tree
• Fundamental data storage structures used in
programming.
• Combines advantages of an ordered array and a
linked list.
• Searching as fast as in ordered array.
• Insertion and deletion as fast as in linked list.
Computer Scientist’s View of a Tree
branches
leaves
root
nodes
Binary Tree
• Any Node can have maximum of two child nodes.
• Each node contains:
▫ A value (some sort of data item)
▫ A reference or pointer to a left child (may be null), and
▫ A reference or pointer to a right child (may be null)
• If not empty, a binary tree has a root node
▫ Every node in the binary tree is reachable from the root
node by a unique path
• A node with neither a left child nor a right child is called a leaf
Binary Tree
7
a
b c
d e
g h i
l
f
j k
Binary Tree
Strictly Binary Tree (SBT):
▫ Every Node has zero or two nodes.
▫ If (n -> LeafNode)
▫ then N=2n-1
Complete Binary Tree (CBT):
▫ All Leaf Nodes are at the same level.
▫ In CBT height of any leaf node is the height of the tree.
▫ N= 20 + 21 + 22 + 23 + ..… + 2L
Binary Tree Operations
Creating a Node:
• The basis of our binary tree node is the following
struct declaration:
9
struct TreeNode
{
int data;
TreeNode *left;
TreeNode *right;
TreeNode *parent
};
TreeNode *P=root;
Binary Tree Operations
• Root: if (P->parent==NULL)
• Leaf: if (P->Left==NULL && P->Right==NULL)
• isLeft (P){
▫ If ((P->Parent)->Left==P)
▫ return true; }
• isRight (P){
▫ If ((P->Parent)->Right==P)
▫ return true; }
• isSibling (P,Q){
▫ If ((P->Parent)==(Q->Parent))
▫ return true; }
10
11
Tree Traversals
• A binary tree is defined recursively: it consists of a root, a
left subtree, and a right subtree
• To traverse the binary tree is to visit each node in the
binary tree exactly once
• Since a binary tree has three “parts,” there are six possible
ways to traverse the binary tree:
▫ root, left, right
▫ left, root, right
▫ left, right, root
▫ root, right, left
▫ right, root, left
▫ right, left, root
Traversing the Tree
• There are three simple ways to traverse a tree:
▫ Inorder
▫ Preorder
▫ Postorder
• Each of these methods is best implemented as a
recursive function.
13
Inorder Traversing - Algorithm
1. Traverse the left subtree, i.e., call Inorder(left-
subtree)
2. Visit the root.
3. Traverse the right subtree, i.e., call
Inorder(right-subtree)
Inorder Traversing
1.The node’s left subtree is
traversed.
2.The node’s data is processed.
3.The node’s right subtree is
traversed.
15
Inorder Traversing - Implementation
• In inorder, the root is visited in the middle
• Here’s an inorder traversal to print out all the
elements in the binary tree:
void inorderPrint(BinaryTree bt) {
inorderPrint(bt.leftChild);
cout<<bt.value;
inorderPrint(bt.rightChild);
}
Non Recursive Inorder Traversing
1) Create an empty stack S.
2) Initialize current node as root
3) Push the current node to S and set current = current->left
until current is NULL
4) If current is NULL and stack is not empty then:
a) Pop the top item from stack.
b) Print the popped item, set current = popped_item->right
c) Go to step 3.
5) If current is NULL and stack is empty then we are done.
17
Uses of Inorder
• In case of binary search trees (BST), Inorder
traversal gives nodes in non-decreasing order. To
get nodes of BST in non-increasing order, a
variation of Inorder traversal where Inorder
traversals reversed can be used
18
Preorder Traversing - Algorithm
1. Visit the root.
2. Traverse the left subtree, i.e., call
Preorder(left-subtree)
3. Traverse the right subtree, i.e., call
Preorder(right-subtree)
Preorder Traversing
1.The node’s data is processed.
2.The node’s left subtree is
traversed.
3.The node’s right subtree is
traversed.
20
Preorder Traversing - Implementation
• In preorder, the root is visited first
• Here’s a preorder traversal to print out all the
elements in the binary tree:
void preorderPrint(BinaryTree bt) {
cout<<bt.value;
preorderPrint(bt.leftChild);
preorderPrint(bt.rightChild);
}
21
Non Recursive Preorder Traversing
• Create a Stack.
• Print the root and push it to Stack and go left
i.e root=root.left and till it hits the NULL.
• If root is null and Stack is empty then
▫ return, we are done.
• Else
▫ Pop the top Node from the Stack and set it as, root
= popped_Node.
▫ Go right, root = root.right.
▫ Go to step 2.
• End If
22
Uses of Preorder
• Preorder traversal is used to create a copy of the
tree.
• Preorder traversal is also used to get prefix
expression on of an expression tree.
23
Postorder traversal - Algorithm
1. Traverse the left subtree, i.e., call
Postorder(left-subtree)
2. Traverse the right subtree, i.e., call
Postorder(right-subtree)
3. Visit the root.
Postorder Traversing
1.The node’s left subtree is
traversed.
2.The node’s right subtree is
traversed.
3.The node’s data is processed.
25
Postorder traversal - Implementation
• In postorder, the root is visited last
• Here’s a postorder traversal to print out all the
elements in the binary tree:
void postorderPrint(BinaryTree bt) {
postorderPrint(bt.leftChild);
postorderPrint(bt.rightChild);
cout<<bt.value;
}
26
Non Recursive Preorder Traversing
• Push root into Stack_One.
• while(Stack_One is not empty)
▫ Pop the node from Stack_One and push it into
Stack_Two.
▫ Push the left and right child nodes of popped node
into Stack_One.
• End Loop
• Pop out all the nodes from Stack_Two and print
it.
27
Uses of Postorder
• Postorder traversal is used to delete the tree.
• Postorder traversal is also useful to get the postfix
expression of an expression tree.
Inserting a Node
• Inserting a Node: The idea is to do iterative level
order traversal of the given tree using queue. If
we find a node whose left child is empty, we
make new key as left child of the node. Else if we
find a node whose right child is empty, we make
new key as right child. We keep traversing the
tree until we find a node whose either left or
right is empty.
28
Inserting a Node - Algorithm
1. If the root is null:
a) Replace empty tree with a new tree with the item at the
root and return true
2. else if the item is equal to root.data
1. The item is already in the tree; return false
3. else if the item is less than root.data
1. Recursively insert the item in the left subtree
4. else
1. Recursively insert the item in the right subtree
Inserting a Node - Representation
Deleting a Node
• While deleting a leaf node we simply find its parent
and set the child pointer that links to it to NULL, and
then free the node's memory.
• But if we are deleting a node that has child nodes
then we must delete the node while at the same
time preserving the subtrees that the node links to.
• There are two possible situations when we are
deleting a non-leaf node:
▫ A) the node has one child, or
▫ B) the node has two children.
31
Deleting a Node - Algorithm
1. Starting at root, find the deepest and rightmost
node in binary tree and node which we want to
delete.
2. Replace the deepest rightmost node’s data with
node to be deleted.
3. Then delete the deepest rightmost node.
Deleting a Node with one child
33
Figure illustrates a tree in which we are
about to delete a node with one subtree.
Deleting a Node with one child
34
Figure shows how we will link the node's
subtree with its parent.
Deleting a Node with two children
35
The problem is not as easily solved,
however, when the node we are about
to delete has two subtrees. For example,
look at Figure .
Deleting a Node with two children
36
We cannot attach both of the node's subtrees
to its parent, so there must be an alternative
solution.
One way is to attach the node's right subtree
to the parent, and then find a position in the
right subtree to attach the left subtree. The
result is shown in Figure.
Deleting a Node
37
To delete a node from the IntBinaryTree, call the public member function
remove. The argument is the value of the node that is to be deleted.
void IntBinaryTree::remove(int num)
{
deleteNode(num, root);
}
The remove member function calls the deleteNode member function. It passes the
value of the node to delete, and the root pointer.
38
Searching the Tree - Algorithm
1. if the root is null:
a) the item is not in the tree; return null
2. Compare the value of target with root.data
3. if they are equal:
a) the target has been found; return the data at the root
4. else if the target is less than root.data:
a) return the result of searching the left subtree
5. else:
a) return the result of searching the right subtree
39
Searching Tree - Performance
• Search a tree is generally O(log n)
• If a tree is not very full, performance will be worse
• Searching a tree with only right subtrees, for example, is O(n)
Summary
• Introduction to Binary Tree
• Operations in Binary tree
• Recursive and Non Recursive Traversal of
Binary/Binary Search Tree
• In-Order Traversal
• Pre-Order Traversal
• Post-Order Traversal
• Insertion of New Node in BST
• Deletion of a Node from BST
• Searching in a Binary Search Tree
References
• https://www.geeksforgeeks.org/binary-tree-data-structure/
• www2.latech.edu/~box/ds/chap8.ppt
• https://www.slideshare.net/vanithachandru/binary-tree-24242122
• https://www.cs.cmu.edu/~adamchik/15-
121/lectures/Trees/trees.html
• https://www.slideshare.net/almario1988/binary-tree-7787268
• https://www.geeksforgeeks.org/binary-tree-data-structure/
• www2.latech.edu/~box/ds/chap8.ppt
• https://www.slideshare.net/vanithachandru/binary-tree-24242122
• https://www.cs.cmu.edu/~adamchik/15-
121/lectures/Trees/trees.html
• https://www.slideshare.net/almario1988/binary-tree-7787268

More Related Content

What's hot

Circular link list.ppt
Circular link list.pptCircular link list.ppt
Circular link list.ppt
Tirthika Bandi
 
linked list (c#)
 linked list (c#) linked list (c#)
linked list (c#)
swajahatr
 
linked list using c
linked list using clinked list using c
linked list using c
Venkat Reddy
 
Singly & Circular Linked list
Singly & Circular Linked listSingly & Circular Linked list
Singly & Circular Linked list
Khulna University of Engineering & Tecnology
 
Operations on linked list
Operations on linked listOperations on linked list
Operations on linked list
Sumathi Kv
 
Mca ii dfs u-3 linklist,stack,queue
Mca ii dfs u-3 linklist,stack,queueMca ii dfs u-3 linklist,stack,queue
Mca ii dfs u-3 linklist,stack,queue
Rai University
 
Linked list
Linked listLinked list
Linked list
Md. Afif Al Mamun
 
Linear data structure concepts
Linear data structure conceptsLinear data structure concepts
Linear data structure concepts
Akila Krishnamoorthy
 
Data Structure (Dynamic Array and Linked List)
Data Structure (Dynamic Array and Linked List)Data Structure (Dynamic Array and Linked List)
Data Structure (Dynamic Array and Linked List)
Adam Mukharil Bachtiar
 
Linklist
LinklistLinklist
linked list
linked listlinked list
linked list
Shaista Qadir
 
Fundamentals of data structures
Fundamentals of data structuresFundamentals of data structures
Fundamentals of data structuresNiraj Agarwal
 
Stacks,queues,linked-list
Stacks,queues,linked-listStacks,queues,linked-list
Stacks,queues,linked-list
pinakspatel
 
Linked list
Linked listLinked list
Linked listVONI
 
Linked lists
Linked listsLinked lists
Linked list
Linked listLinked list
Linked list
RahulGandhi110
 
Link list presentation slide(Daffodil international university)
Link list presentation slide(Daffodil international university)Link list presentation slide(Daffodil international university)
Link list presentation slide(Daffodil international university)
shah alom
 
Linked List Static and Dynamic Memory Allocation
Linked List Static and Dynamic Memory AllocationLinked List Static and Dynamic Memory Allocation
Linked List Static and Dynamic Memory Allocation
Prof Ansari
 

What's hot (19)

Algo>ADT list & linked list
Algo>ADT list & linked listAlgo>ADT list & linked list
Algo>ADT list & linked list
 
Circular link list.ppt
Circular link list.pptCircular link list.ppt
Circular link list.ppt
 
linked list (c#)
 linked list (c#) linked list (c#)
linked list (c#)
 
linked list using c
linked list using clinked list using c
linked list using c
 
Singly & Circular Linked list
Singly & Circular Linked listSingly & Circular Linked list
Singly & Circular Linked list
 
Operations on linked list
Operations on linked listOperations on linked list
Operations on linked list
 
Mca ii dfs u-3 linklist,stack,queue
Mca ii dfs u-3 linklist,stack,queueMca ii dfs u-3 linklist,stack,queue
Mca ii dfs u-3 linklist,stack,queue
 
Linked list
Linked listLinked list
Linked list
 
Linear data structure concepts
Linear data structure conceptsLinear data structure concepts
Linear data structure concepts
 
Data Structure (Dynamic Array and Linked List)
Data Structure (Dynamic Array and Linked List)Data Structure (Dynamic Array and Linked List)
Data Structure (Dynamic Array and Linked List)
 
Linklist
LinklistLinklist
Linklist
 
linked list
linked listlinked list
linked list
 
Fundamentals of data structures
Fundamentals of data structuresFundamentals of data structures
Fundamentals of data structures
 
Stacks,queues,linked-list
Stacks,queues,linked-listStacks,queues,linked-list
Stacks,queues,linked-list
 
Linked list
Linked listLinked list
Linked list
 
Linked lists
Linked listsLinked lists
Linked lists
 
Linked list
Linked listLinked list
Linked list
 
Link list presentation slide(Daffodil international university)
Link list presentation slide(Daffodil international university)Link list presentation slide(Daffodil international university)
Link list presentation slide(Daffodil international university)
 
Linked List Static and Dynamic Memory Allocation
Linked List Static and Dynamic Memory AllocationLinked List Static and Dynamic Memory Allocation
Linked List Static and Dynamic Memory Allocation
 

Similar to Binary tree

Binary trees
Binary treesBinary trees
Binary treesAmit Vats
 
TREE DATA STRUCTURE SLIDES dsa dsa .pptx
TREE DATA STRUCTURE SLIDES dsa dsa .pptxTREE DATA STRUCTURE SLIDES dsa dsa .pptx
TREE DATA STRUCTURE SLIDES dsa dsa .pptx
asimshahzad8611
 
Introduction to data structure by anil dutt
Introduction to data structure by anil duttIntroduction to data structure by anil dutt
Introduction to data structure by anil dutt
Anil Dutt
 
Trees in data structure
Trees in data structureTrees in data structure
Trees in data structure
Anusruti Mitra
 
1.1 binary tree
1.1 binary tree1.1 binary tree
1.1 binary tree
Krish_ver2
 
Binary search tree
Binary search treeBinary search tree
Binary search tree
Sana Yameen
 
Binary Tree - Algorithms
Binary Tree - Algorithms Binary Tree - Algorithms
Binary Tree - Algorithms
CourseHunt
 
Trees second part in data structures with examples
Trees second part in data structures with examplesTrees second part in data structures with examples
Trees second part in data structures with examples
rupanaveen24
 
L 17 ct1120
L 17 ct1120L 17 ct1120
L 17 ct1120
Zia Ush Shamszaman
 
Binary Search Tree
Binary Search TreeBinary Search Tree
Binary Search Tree
sagar yadav
 
BINARY SEARCH TREE
BINARY SEARCH TREEBINARY SEARCH TREE
BINARY SEARCH TREE
ER Punit Jain
 
Fundamentalsofdatastructures 110501104205-phpapp02
Fundamentalsofdatastructures 110501104205-phpapp02Fundamentalsofdatastructures 110501104205-phpapp02
Fundamentalsofdatastructures 110501104205-phpapp02Getachew Ganfur
 
tree-160731205832.pptx
tree-160731205832.pptxtree-160731205832.pptx
tree-160731205832.pptx
MouDhara1
 
Binary Search Tree.pptx
Binary Search Tree.pptxBinary Search Tree.pptx
Binary Search Tree.pptx
RaaviKapoor
 
Tree traversal techniques
Tree traversal techniquesTree traversal techniques
Tree traversal techniques
Syed Zaid Irshad
 
Lecture 7-BinarySearchTrees.ppt
Lecture 7-BinarySearchTrees.pptLecture 7-BinarySearchTrees.ppt
Lecture 7-BinarySearchTrees.ppt
DrBashirMSaad
 
Tree and binary tree
Tree and binary treeTree and binary tree
Tree and binary tree
Zaid Shabbir
 
Search tree,Tree and binary tree and heap tree
Search tree,Tree  and binary tree and heap treeSearch tree,Tree  and binary tree and heap tree
Search tree,Tree and binary tree and heap tree
zia eagle
 

Similar to Binary tree (20)

Binary trees
Binary treesBinary trees
Binary trees
 
TREE DATA STRUCTURE SLIDES dsa dsa .pptx
TREE DATA STRUCTURE SLIDES dsa dsa .pptxTREE DATA STRUCTURE SLIDES dsa dsa .pptx
TREE DATA STRUCTURE SLIDES dsa dsa .pptx
 
Introduction to data structure by anil dutt
Introduction to data structure by anil duttIntroduction to data structure by anil dutt
Introduction to data structure by anil dutt
 
Trees in data structure
Trees in data structureTrees in data structure
Trees in data structure
 
1.1 binary tree
1.1 binary tree1.1 binary tree
1.1 binary tree
 
Binary search tree
Binary search treeBinary search tree
Binary search tree
 
Binary Tree - Algorithms
Binary Tree - Algorithms Binary Tree - Algorithms
Binary Tree - Algorithms
 
Trees second part in data structures with examples
Trees second part in data structures with examplesTrees second part in data structures with examples
Trees second part in data structures with examples
 
L 17 ct1120
L 17 ct1120L 17 ct1120
L 17 ct1120
 
Binary Search Tree
Binary Search TreeBinary Search Tree
Binary Search Tree
 
Unit iv data structure-converted
Unit  iv data structure-convertedUnit  iv data structure-converted
Unit iv data structure-converted
 
BINARY SEARCH TREE
BINARY SEARCH TREEBINARY SEARCH TREE
BINARY SEARCH TREE
 
Fundamentalsofdatastructures 110501104205-phpapp02
Fundamentalsofdatastructures 110501104205-phpapp02Fundamentalsofdatastructures 110501104205-phpapp02
Fundamentalsofdatastructures 110501104205-phpapp02
 
Binary searchtrees
Binary searchtreesBinary searchtrees
Binary searchtrees
 
tree-160731205832.pptx
tree-160731205832.pptxtree-160731205832.pptx
tree-160731205832.pptx
 
Binary Search Tree.pptx
Binary Search Tree.pptxBinary Search Tree.pptx
Binary Search Tree.pptx
 
Tree traversal techniques
Tree traversal techniquesTree traversal techniques
Tree traversal techniques
 
Lecture 7-BinarySearchTrees.ppt
Lecture 7-BinarySearchTrees.pptLecture 7-BinarySearchTrees.ppt
Lecture 7-BinarySearchTrees.ppt
 
Tree and binary tree
Tree and binary treeTree and binary tree
Tree and binary tree
 
Search tree,Tree and binary tree and heap tree
Search tree,Tree  and binary tree and heap treeSearch tree,Tree  and binary tree and heap tree
Search tree,Tree and binary tree and heap tree
 

More from Afaq Mansoor Khan

Feature Selection - Natural Language Processing
Feature Selection - Natural Language ProcessingFeature Selection - Natural Language Processing
Feature Selection - Natural Language Processing
Afaq Mansoor Khan
 
WiFi vs LiFi - A Comparison
WiFi vs LiFi - A ComparisonWiFi vs LiFi - A Comparison
WiFi vs LiFi - A Comparison
Afaq Mansoor Khan
 
Role of Electronic Media in Pakistan
Role of Electronic Media in PakistanRole of Electronic Media in Pakistan
Role of Electronic Media in Pakistan
Afaq Mansoor Khan
 
Agile Testing - Approach and Strategies
Agile Testing - Approach and StrategiesAgile Testing - Approach and Strategies
Agile Testing - Approach and Strategies
Afaq Mansoor Khan
 
Ethical Hacking - An Overview
Ethical Hacking - An OverviewEthical Hacking - An Overview
Ethical Hacking - An Overview
Afaq Mansoor Khan
 
Software Architecture Design Decisions
Software Architecture Design DecisionsSoftware Architecture Design Decisions
Software Architecture Design Decisions
Afaq Mansoor Khan
 
How to Design an Algorithm
How to Design an AlgorithmHow to Design an Algorithm
How to Design an Algorithm
Afaq Mansoor Khan
 
Software Quality Qssurance, Scrum and Linkedin
Software Quality Qssurance, Scrum and LinkedinSoftware Quality Qssurance, Scrum and Linkedin
Software Quality Qssurance, Scrum and Linkedin
Afaq Mansoor Khan
 
Quick sort
Quick sortQuick sort
Quick sort
Afaq Mansoor Khan
 
.Physics presentation - Asteroids
.Physics presentation - Asteroids.Physics presentation - Asteroids
.Physics presentation - Asteroids
Afaq Mansoor Khan
 
Graph Data Structure
Graph Data StructureGraph Data Structure
Graph Data Structure
Afaq Mansoor Khan
 
AVL Tree Data Structure
AVL Tree Data StructureAVL Tree Data Structure
AVL Tree Data Structure
Afaq Mansoor Khan
 
Queue Data Structure
Queue Data StructureQueue Data Structure
Queue Data Structure
Afaq Mansoor Khan
 
Prefix, Infix and Post-fix Notations
Prefix, Infix and Post-fix NotationsPrefix, Infix and Post-fix Notations
Prefix, Infix and Post-fix Notations
Afaq Mansoor Khan
 
Stack Data Structure
Stack Data StructureStack Data Structure
Stack Data Structure
Afaq Mansoor Khan
 
Dynamic Memory & Linked Lists
Dynamic Memory & Linked ListsDynamic Memory & Linked Lists
Dynamic Memory & Linked Lists
Afaq Mansoor Khan
 
Sorting Algorithms
Sorting AlgorithmsSorting Algorithms
Sorting Algorithms
Afaq Mansoor Khan
 
Recursion and Sorting Algorithms
Recursion and Sorting AlgorithmsRecursion and Sorting Algorithms
Recursion and Sorting Algorithms
Afaq Mansoor Khan
 
Searching Algorithms
Searching AlgorithmsSearching Algorithms
Searching Algorithms
Afaq Mansoor Khan
 
Introduction to Data Structures & Algorithms
Introduction to Data Structures & AlgorithmsIntroduction to Data Structures & Algorithms
Introduction to Data Structures & Algorithms
Afaq Mansoor Khan
 

More from Afaq Mansoor Khan (20)

Feature Selection - Natural Language Processing
Feature Selection - Natural Language ProcessingFeature Selection - Natural Language Processing
Feature Selection - Natural Language Processing
 
WiFi vs LiFi - A Comparison
WiFi vs LiFi - A ComparisonWiFi vs LiFi - A Comparison
WiFi vs LiFi - A Comparison
 
Role of Electronic Media in Pakistan
Role of Electronic Media in PakistanRole of Electronic Media in Pakistan
Role of Electronic Media in Pakistan
 
Agile Testing - Approach and Strategies
Agile Testing - Approach and StrategiesAgile Testing - Approach and Strategies
Agile Testing - Approach and Strategies
 
Ethical Hacking - An Overview
Ethical Hacking - An OverviewEthical Hacking - An Overview
Ethical Hacking - An Overview
 
Software Architecture Design Decisions
Software Architecture Design DecisionsSoftware Architecture Design Decisions
Software Architecture Design Decisions
 
How to Design an Algorithm
How to Design an AlgorithmHow to Design an Algorithm
How to Design an Algorithm
 
Software Quality Qssurance, Scrum and Linkedin
Software Quality Qssurance, Scrum and LinkedinSoftware Quality Qssurance, Scrum and Linkedin
Software Quality Qssurance, Scrum and Linkedin
 
Quick sort
Quick sortQuick sort
Quick sort
 
.Physics presentation - Asteroids
.Physics presentation - Asteroids.Physics presentation - Asteroids
.Physics presentation - Asteroids
 
Graph Data Structure
Graph Data StructureGraph Data Structure
Graph Data Structure
 
AVL Tree Data Structure
AVL Tree Data StructureAVL Tree Data Structure
AVL Tree Data Structure
 
Queue Data Structure
Queue Data StructureQueue Data Structure
Queue Data Structure
 
Prefix, Infix and Post-fix Notations
Prefix, Infix and Post-fix NotationsPrefix, Infix and Post-fix Notations
Prefix, Infix and Post-fix Notations
 
Stack Data Structure
Stack Data StructureStack Data Structure
Stack Data Structure
 
Dynamic Memory & Linked Lists
Dynamic Memory & Linked ListsDynamic Memory & Linked Lists
Dynamic Memory & Linked Lists
 
Sorting Algorithms
Sorting AlgorithmsSorting Algorithms
Sorting Algorithms
 
Recursion and Sorting Algorithms
Recursion and Sorting AlgorithmsRecursion and Sorting Algorithms
Recursion and Sorting Algorithms
 
Searching Algorithms
Searching AlgorithmsSearching Algorithms
Searching Algorithms
 
Introduction to Data Structures & Algorithms
Introduction to Data Structures & AlgorithmsIntroduction to Data Structures & Algorithms
Introduction to Data Structures & Algorithms
 

Recently uploaded

Cyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdfCyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdf
Cyanic lab
 
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
Juraj Vysvader
 
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Globus
 
Into the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdfInto the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdf
Ortus Solutions, Corp
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
Max Andersen
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2
 
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamOpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
takuyayamamoto1800
 
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns
 
Corporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMSCorporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMS
Tendenci - The Open Source AMS (Association Management Software)
 
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
XfilesPro
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
abdulrafaychaudhry
 
Strategies for Successful Data Migration Tools.pptx
Strategies for Successful Data Migration Tools.pptxStrategies for Successful Data Migration Tools.pptx
Strategies for Successful Data Migration Tools.pptx
varshanayak241
 
Explore Modern SharePoint Templates for 2024
Explore Modern SharePoint Templates for 2024Explore Modern SharePoint Templates for 2024
Explore Modern SharePoint Templates for 2024
Sharepoint Designs
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
Georgi Kodinov
 
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
Tier1 app
 
Using IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New ZealandUsing IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New Zealand
IES VE
 
Why React Native as a Strategic Advantage for Startup Innovation.pdf
Why React Native as a Strategic Advantage for Startup Innovation.pdfWhy React Native as a Strategic Advantage for Startup Innovation.pdf
Why React Native as a Strategic Advantage for Startup Innovation.pdf
ayushiqss
 
Accelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessAccelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with Platformless
WSO2
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
Matt Welsh
 
BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
Ortus Solutions, Corp
 

Recently uploaded (20)

Cyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdfCyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdf
 
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
 
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
 
Into the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdfInto the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdf
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
 
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamOpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
 
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology Solutions
 
Corporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMSCorporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMS
 
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
 
Strategies for Successful Data Migration Tools.pptx
Strategies for Successful Data Migration Tools.pptxStrategies for Successful Data Migration Tools.pptx
Strategies for Successful Data Migration Tools.pptx
 
Explore Modern SharePoint Templates for 2024
Explore Modern SharePoint Templates for 2024Explore Modern SharePoint Templates for 2024
Explore Modern SharePoint Templates for 2024
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
 
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
 
Using IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New ZealandUsing IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New Zealand
 
Why React Native as a Strategic Advantage for Startup Innovation.pdf
Why React Native as a Strategic Advantage for Startup Innovation.pdfWhy React Native as a Strategic Advantage for Startup Innovation.pdf
Why React Native as a Strategic Advantage for Startup Innovation.pdf
 
Accelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessAccelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with Platformless
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
 
BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
 

Binary tree

  • 1. Binary Tree Prepared by: Afaq Mansoor Khan BSSE III- Group A Session 2017-21 IMSciences, Peshawar.
  • 2. Last Lecture Summary • Introduction to Queue Data Structure • Types of Queue Data Structures • Circular QUEUE and its Operations • Double Ended QUEUE and its operations
  • 3. Objectives Overview • Introduction to Binary Tree • Operations in Binary tree • Recursive and Non Recursive Traversal of Binary/Binary Search Tree • In-Order Traversal • Pre-Order Traversal • Post-Order Traversal • Insertion of New Node in BST • Deletion of a Node from BST • Searching in a Binary Search Tree
  • 4. Introduction to Tree • Fundamental data storage structures used in programming. • Combines advantages of an ordered array and a linked list. • Searching as fast as in ordered array. • Insertion and deletion as fast as in linked list.
  • 5. Computer Scientist’s View of a Tree branches leaves root nodes
  • 6. Binary Tree • Any Node can have maximum of two child nodes. • Each node contains: ▫ A value (some sort of data item) ▫ A reference or pointer to a left child (may be null), and ▫ A reference or pointer to a right child (may be null) • If not empty, a binary tree has a root node ▫ Every node in the binary tree is reachable from the root node by a unique path • A node with neither a left child nor a right child is called a leaf
  • 7. Binary Tree 7 a b c d e g h i l f j k
  • 8. Binary Tree Strictly Binary Tree (SBT): ▫ Every Node has zero or two nodes. ▫ If (n -> LeafNode) ▫ then N=2n-1 Complete Binary Tree (CBT): ▫ All Leaf Nodes are at the same level. ▫ In CBT height of any leaf node is the height of the tree. ▫ N= 20 + 21 + 22 + 23 + ..… + 2L
  • 9. Binary Tree Operations Creating a Node: • The basis of our binary tree node is the following struct declaration: 9 struct TreeNode { int data; TreeNode *left; TreeNode *right; TreeNode *parent }; TreeNode *P=root;
  • 10. Binary Tree Operations • Root: if (P->parent==NULL) • Leaf: if (P->Left==NULL && P->Right==NULL) • isLeft (P){ ▫ If ((P->Parent)->Left==P) ▫ return true; } • isRight (P){ ▫ If ((P->Parent)->Right==P) ▫ return true; } • isSibling (P,Q){ ▫ If ((P->Parent)==(Q->Parent)) ▫ return true; } 10
  • 11. 11 Tree Traversals • A binary tree is defined recursively: it consists of a root, a left subtree, and a right subtree • To traverse the binary tree is to visit each node in the binary tree exactly once • Since a binary tree has three “parts,” there are six possible ways to traverse the binary tree: ▫ root, left, right ▫ left, root, right ▫ left, right, root ▫ root, right, left ▫ right, root, left ▫ right, left, root
  • 12. Traversing the Tree • There are three simple ways to traverse a tree: ▫ Inorder ▫ Preorder ▫ Postorder • Each of these methods is best implemented as a recursive function.
  • 13. 13 Inorder Traversing - Algorithm 1. Traverse the left subtree, i.e., call Inorder(left- subtree) 2. Visit the root. 3. Traverse the right subtree, i.e., call Inorder(right-subtree)
  • 14. Inorder Traversing 1.The node’s left subtree is traversed. 2.The node’s data is processed. 3.The node’s right subtree is traversed.
  • 15. 15 Inorder Traversing - Implementation • In inorder, the root is visited in the middle • Here’s an inorder traversal to print out all the elements in the binary tree: void inorderPrint(BinaryTree bt) { inorderPrint(bt.leftChild); cout<<bt.value; inorderPrint(bt.rightChild); }
  • 16. Non Recursive Inorder Traversing 1) Create an empty stack S. 2) Initialize current node as root 3) Push the current node to S and set current = current->left until current is NULL 4) If current is NULL and stack is not empty then: a) Pop the top item from stack. b) Print the popped item, set current = popped_item->right c) Go to step 3. 5) If current is NULL and stack is empty then we are done.
  • 17. 17 Uses of Inorder • In case of binary search trees (BST), Inorder traversal gives nodes in non-decreasing order. To get nodes of BST in non-increasing order, a variation of Inorder traversal where Inorder traversals reversed can be used
  • 18. 18 Preorder Traversing - Algorithm 1. Visit the root. 2. Traverse the left subtree, i.e., call Preorder(left-subtree) 3. Traverse the right subtree, i.e., call Preorder(right-subtree)
  • 19. Preorder Traversing 1.The node’s data is processed. 2.The node’s left subtree is traversed. 3.The node’s right subtree is traversed.
  • 20. 20 Preorder Traversing - Implementation • In preorder, the root is visited first • Here’s a preorder traversal to print out all the elements in the binary tree: void preorderPrint(BinaryTree bt) { cout<<bt.value; preorderPrint(bt.leftChild); preorderPrint(bt.rightChild); }
  • 21. 21 Non Recursive Preorder Traversing • Create a Stack. • Print the root and push it to Stack and go left i.e root=root.left and till it hits the NULL. • If root is null and Stack is empty then ▫ return, we are done. • Else ▫ Pop the top Node from the Stack and set it as, root = popped_Node. ▫ Go right, root = root.right. ▫ Go to step 2. • End If
  • 22. 22 Uses of Preorder • Preorder traversal is used to create a copy of the tree. • Preorder traversal is also used to get prefix expression on of an expression tree.
  • 23. 23 Postorder traversal - Algorithm 1. Traverse the left subtree, i.e., call Postorder(left-subtree) 2. Traverse the right subtree, i.e., call Postorder(right-subtree) 3. Visit the root.
  • 24. Postorder Traversing 1.The node’s left subtree is traversed. 2.The node’s right subtree is traversed. 3.The node’s data is processed.
  • 25. 25 Postorder traversal - Implementation • In postorder, the root is visited last • Here’s a postorder traversal to print out all the elements in the binary tree: void postorderPrint(BinaryTree bt) { postorderPrint(bt.leftChild); postorderPrint(bt.rightChild); cout<<bt.value; }
  • 26. 26 Non Recursive Preorder Traversing • Push root into Stack_One. • while(Stack_One is not empty) ▫ Pop the node from Stack_One and push it into Stack_Two. ▫ Push the left and right child nodes of popped node into Stack_One. • End Loop • Pop out all the nodes from Stack_Two and print it.
  • 27. 27 Uses of Postorder • Postorder traversal is used to delete the tree. • Postorder traversal is also useful to get the postfix expression of an expression tree.
  • 28. Inserting a Node • Inserting a Node: The idea is to do iterative level order traversal of the given tree using queue. If we find a node whose left child is empty, we make new key as left child of the node. Else if we find a node whose right child is empty, we make new key as right child. We keep traversing the tree until we find a node whose either left or right is empty. 28
  • 29. Inserting a Node - Algorithm 1. If the root is null: a) Replace empty tree with a new tree with the item at the root and return true 2. else if the item is equal to root.data 1. The item is already in the tree; return false 3. else if the item is less than root.data 1. Recursively insert the item in the left subtree 4. else 1. Recursively insert the item in the right subtree
  • 30. Inserting a Node - Representation
  • 31. Deleting a Node • While deleting a leaf node we simply find its parent and set the child pointer that links to it to NULL, and then free the node's memory. • But if we are deleting a node that has child nodes then we must delete the node while at the same time preserving the subtrees that the node links to. • There are two possible situations when we are deleting a non-leaf node: ▫ A) the node has one child, or ▫ B) the node has two children. 31
  • 32. Deleting a Node - Algorithm 1. Starting at root, find the deepest and rightmost node in binary tree and node which we want to delete. 2. Replace the deepest rightmost node’s data with node to be deleted. 3. Then delete the deepest rightmost node.
  • 33. Deleting a Node with one child 33 Figure illustrates a tree in which we are about to delete a node with one subtree.
  • 34. Deleting a Node with one child 34 Figure shows how we will link the node's subtree with its parent.
  • 35. Deleting a Node with two children 35 The problem is not as easily solved, however, when the node we are about to delete has two subtrees. For example, look at Figure .
  • 36. Deleting a Node with two children 36 We cannot attach both of the node's subtrees to its parent, so there must be an alternative solution. One way is to attach the node's right subtree to the parent, and then find a position in the right subtree to attach the left subtree. The result is shown in Figure.
  • 37. Deleting a Node 37 To delete a node from the IntBinaryTree, call the public member function remove. The argument is the value of the node that is to be deleted. void IntBinaryTree::remove(int num) { deleteNode(num, root); } The remove member function calls the deleteNode member function. It passes the value of the node to delete, and the root pointer.
  • 38. 38 Searching the Tree - Algorithm 1. if the root is null: a) the item is not in the tree; return null 2. Compare the value of target with root.data 3. if they are equal: a) the target has been found; return the data at the root 4. else if the target is less than root.data: a) return the result of searching the left subtree 5. else: a) return the result of searching the right subtree
  • 39. 39 Searching Tree - Performance • Search a tree is generally O(log n) • If a tree is not very full, performance will be worse • Searching a tree with only right subtrees, for example, is O(n)
  • 40. Summary • Introduction to Binary Tree • Operations in Binary tree • Recursive and Non Recursive Traversal of Binary/Binary Search Tree • In-Order Traversal • Pre-Order Traversal • Post-Order Traversal • Insertion of New Node in BST • Deletion of a Node from BST • Searching in a Binary Search Tree
  • 41. References • https://www.geeksforgeeks.org/binary-tree-data-structure/ • www2.latech.edu/~box/ds/chap8.ppt • https://www.slideshare.net/vanithachandru/binary-tree-24242122 • https://www.cs.cmu.edu/~adamchik/15- 121/lectures/Trees/trees.html • https://www.slideshare.net/almario1988/binary-tree-7787268 • https://www.geeksforgeeks.org/binary-tree-data-structure/ • www2.latech.edu/~box/ds/chap8.ppt • https://www.slideshare.net/vanithachandru/binary-tree-24242122 • https://www.cs.cmu.edu/~adamchik/15- 121/lectures/Trees/trees.html • https://www.slideshare.net/almario1988/binary-tree-7787268