SlideShare ist ein Scribd-Unternehmen logo
1 von 41
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

Weitere ähnliche Inhalte

Was ist angesagt?

Circular link list.ppt
Circular link list.pptCircular link list.ppt
Circular link list.pptTirthika 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 cVenkat Reddy
 
Operations on linked list
Operations on linked listOperations on linked list
Operations on linked listSumathi 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,queueRai University
 
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
 
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-listpinakspatel
 
Linked list
Linked listLinked list
Linked listVONI
 
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 AllocationProf Ansari
 

Was ist angesagt? (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
 

Ähnlich wie 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 .pptxasimshahzad8611
 
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 duttAnil Dutt
 
Trees in data structure
Trees in data structureTrees in data structure
Trees in data structureAnusruti Mitra
 
1.1 binary tree
1.1 binary tree1.1 binary tree
1.1 binary treeKrish_ver2
 
Binary search tree
Binary search treeBinary search tree
Binary search treeSana Yameen
 
Binary Tree - Algorithms
Binary Tree - Algorithms Binary Tree - Algorithms
Binary Tree - Algorithms CourseHunt
 
Binary Search Tree
Binary Search TreeBinary Search Tree
Binary Search Treesagar yadav
 
Fundamentalsofdatastructures 110501104205-phpapp02
Fundamentalsofdatastructures 110501104205-phpapp02Fundamentalsofdatastructures 110501104205-phpapp02
Fundamentalsofdatastructures 110501104205-phpapp02Getachew Ganfur
 
tree-160731205832.pptx
tree-160731205832.pptxtree-160731205832.pptx
tree-160731205832.pptxMouDhara1
 
Binary Search Tree.pptx
Binary Search Tree.pptxBinary Search Tree.pptx
Binary Search Tree.pptxRaaviKapoor
 
Lecture 7-BinarySearchTrees.ppt
Lecture 7-BinarySearchTrees.pptLecture 7-BinarySearchTrees.ppt
Lecture 7-BinarySearchTrees.pptDrBashirMSaad
 
Tree and binary tree
Tree and binary treeTree and binary tree
Tree and binary treeZaid 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 treezia eagle
 

Ähnlich wie 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
 
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
 
Binary tree
Binary treeBinary tree
Binary tree
 

Mehr von Afaq Mansoor Khan

Feature Selection - Natural Language Processing
Feature Selection - Natural Language ProcessingFeature Selection - Natural Language Processing
Feature Selection - Natural Language ProcessingAfaq Mansoor Khan
 
Role of Electronic Media in Pakistan
Role of Electronic Media in PakistanRole of Electronic Media in Pakistan
Role of Electronic Media in PakistanAfaq Mansoor Khan
 
Agile Testing - Approach and Strategies
Agile Testing - Approach and StrategiesAgile Testing - Approach and Strategies
Agile Testing - Approach and StrategiesAfaq Mansoor Khan
 
Ethical Hacking - An Overview
Ethical Hacking - An OverviewEthical Hacking - An Overview
Ethical Hacking - An OverviewAfaq Mansoor Khan
 
Software Architecture Design Decisions
Software Architecture Design DecisionsSoftware Architecture Design Decisions
Software Architecture Design DecisionsAfaq Mansoor Khan
 
Software Quality Qssurance, Scrum and Linkedin
Software Quality Qssurance, Scrum and LinkedinSoftware Quality Qssurance, Scrum and Linkedin
Software Quality Qssurance, Scrum and LinkedinAfaq Mansoor Khan
 
.Physics presentation - Asteroids
.Physics presentation - Asteroids.Physics presentation - Asteroids
.Physics presentation - AsteroidsAfaq Mansoor Khan
 
Prefix, Infix and Post-fix Notations
Prefix, Infix and Post-fix NotationsPrefix, Infix and Post-fix Notations
Prefix, Infix and Post-fix NotationsAfaq Mansoor Khan
 
Dynamic Memory & Linked Lists
Dynamic Memory & Linked ListsDynamic Memory & Linked Lists
Dynamic Memory & Linked ListsAfaq Mansoor Khan
 
Recursion and Sorting Algorithms
Recursion and Sorting AlgorithmsRecursion and Sorting Algorithms
Recursion and Sorting AlgorithmsAfaq Mansoor Khan
 
Introduction to Data Structures & Algorithms
Introduction to Data Structures & AlgorithmsIntroduction to Data Structures & Algorithms
Introduction to Data Structures & AlgorithmsAfaq Mansoor Khan
 

Mehr von 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
 

Kürzlich hochgeladen

Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
Clustering techniques data mining book ....
Clustering techniques data mining book ....Clustering techniques data mining book ....
Clustering techniques data mining book ....ShaimaaMohamedGalal
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️anilsa9823
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
Active Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfActive Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfCionsystems
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 

Kürzlich hochgeladen (20)

Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
Clustering techniques data mining book ....
Clustering techniques data mining book ....Clustering techniques data mining book ....
Clustering techniques data mining book ....
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
Exploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the ProcessExploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the Process
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Active Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfActive Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdf
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 

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