SlideShare a Scribd company logo
1 of 49
1
Binary Trees
2
Definition and Applications of
Binary Trees
• A binary tree is a non-linear linked list
where each node may point to two other
nodes.
3
Definition and Applications of
Binary Trees
• It is anchored at the top by a tree pointer,
which is like the head pointer in a linked
list.
• The first node in the list is called the root
node.
• The root node has pointers to two other
nodes, which are called children, or child
nodes.
4
Definition and Applications of
Binary Trees
• A node that has no children is called a leaf
node.
• All pointers that do not point to a node are
set to NULL.
5
Definition and Applications of
Binary Trees
• Binary trees can be divided into subtrees. A
subtree is an entire branch of the tree, from
one particular node down.
6
Definition and Applications of
Binary Trees
• Binary trees are excellent data structures for
searching large amounts of information.
They are commonly used in database
applications to organize key values that
index database records.
• When used to facilitate searches, a binary
tree is called a binary search tree.
7
Definition and Applications of
Binary Trees
• Information is stored in binary search trees in a
way that makes a binary search simple. For
example, look at Figure 3.
Values are stored in a binary tree so
that a node's left child holds data
whose value is less than the node's
data, and the node's right child holds
data whose value is greater tan the
node's data.
8
Definition and Applications of
Binary Trees
• It is also true that all the nodes to the left of a node
hold values less than the node's value. Likewise,
all the nodes to the right of a node hold values that
are greater than the node's data.
• When an application is searching a binary tree, it
starts at the root node. If the root node does not
hold the search value, the application branches
either to the left or right child, depending on
whether the search value is less than or grater than
the value at the root node.
9
Definition and Applications of
Binary Trees
• This process continues until the value is found.
Figure 4 illustrates the search pattern for finding
the value P in the binary tree.
10
Binary Search Tree Operations
• Creating a Node: We will demonstrate binary tree
operations using the IntBinaryTree class.
• The basis of our binary tree node is the following
struct declaration:
struct TreeNode
{
int value;
TreeNode *left;
TreeNode *right;
};
• The struct is implemented in the class shown next…
11
IntBinaryTree.h
class IntBinaryTree
{
public:
struct TreeNode
{
int value;
TreeNode *left;
TreeNode *right;
};
TreeNode *root;
void destroySubTree(TreeNode *);
void deleteNode(int, TreeNode *&);
void makeDeletion(TreeNode *&);
void displayInOrder(TreeNode *);
void displayPreOrder(TreeNode *);
void displayPostOrder(TreeNode *);
12
IntBinaryTree.h
(continued)
public:
IntBinaryTree() // Constructor
{ root = NULL; }
~IntBinaryTree() // Destructor
{ destroySubTree(root); }
void insertNode(int);
bool searchNode(int);
void remove(int);
void showNodesInOrder(void)
{ displayInOrder(root); }
void showNodesPreOrder()
{ displayPreOrder(root); }
void showNodesPostOrder()
{ displayPostOrder(root); }
};
13
Binary Search Tree Operations
• Inserting a Node:First, a new node is allocated
and its value member is initialized with the new
value.
• The left and right child pointers are set to NULL,
because all nodes must be inserted as leaf nodes.
• Next, we determine if the tree is empty. If so, we
simply make root point to it, and there is nothing
else to be done. But, if there are nodes in the tree,
we must find the new node's proper insertion
point.
14
Binary Search Tree Operations
• If the new value is less than the root node's
value, we know it will be inserted somewhere in
the left subtree. Otherwise, the value will be
inserted into the right subtree.
• We simply traverse the subtree, comparing each
node along the way with the new node's value, and
deciding if we should continue to the left or the
right.
• When we reach a child pointer that is set to
NULL, we have found out insertion point.
15
The insertNode Member
Function
void IntBinaryTree::insertNode(int num)
{
TreeNode *newNode, // Pointer to a new node
*nodePtr; // Pointer to traverse the tree
// Create a new node
newNode = new TreeNode;
newNode->value = num;
newNode->left = newNode->right = NULL;
if (!root) // Is the tree empty?
root = newNode;
else
{
nodePtr = root;
16
The insertNode Member
Function
while (nodePtr != NULL)
{
if (num < nodePtr->value)
{
if (nodePtr->left)
nodePtr = nodePtr->left;
else
{
nodePtr->left = newNode;
break;
}
}
17
The insertNode Member
Function
else if (num > nodePtr->value)
{
if (nodePtr->right)
nodePtr = nodePtr->right;
else
{
nodePtr->right = newNode;
break;
}
}
else
{
cout << "Duplicate value found in tree.n";
break;
}
}
}
}
18
Program 1
// This program builds a binary tree with 5 nodes.
#include <iostream.h>
#include "IntBinaryTree.h“
void main(void)
{
IntBinaryTree tree;
cout << "Inserting nodes. ";
tree.insertNode(5);
tree.insertNode(8);
tree.insertNode(3);
tree.insertNode(12);
tree.insertNode(9);
cout << "Done.n";
}
19
Program 1
Figure 5 shows the structure of the binary tree built by the program.
Note: The shape of the tree is
determined by the order in
which the values are inserted.
The root node in the diagram
above holds the value 5 because
that was the first value inserted.
20
Traversing the Tree
• There are three common methods for
traversing a binary tree and processing the
value of each node:
– inorder
– preorder
– postorder
• Each of these methods is best implemented
as a recursive function.
21
Inorder Traversal
1. The node’s left subtree is traversed.
2. The node’s data is processed.
3. The node’s right subtree is traversed.
22
Preorder Traversal
1. The node’s data is processed.
2. The node’s left subtree is traversed.
3. The node’s right subtree is traversed.
23
Postorder Traversal
1. The node’s left subtree is traversed.
2. The node’s right subtree is traversed.
3. The node’s data is processed.
24
The displayInOrder
Member Function
void IntBinaryTree::displayInOrder(TreeNode *nodePtr)
{
if (nodePtr)
{
displayInOrder(nodePtr->left);
cout << nodePtr->value << endl;
displayInOrder(nodePtr->right);
}
}
25
The displayPreOrder
Member Function
void IntBinaryTree::displayPreOrder(TreeNode *nodePtr)
{
if (nodePtr)
{
cout << nodePtr->value << endl;
displayPreOrder(nodePtr->left);
displayPreOrder(nodePtr->right);
}
}
26
The displayPostOrder
Member Function
void IntBinaryTree::displayPostOrder(TreeNode *nodePtr)
{
if (nodePtr)
{
displayPostOrder(nodePtr->left);
displayPostOrder(nodePtr->right);
cout << nodePtr->value << endl;
}
}
27
Program 2
// This program builds a binary tree with 5 nodes.
// The nodes are displayed with inorder, preorder,
// and postorder algorithms.
#include <iostream.h>
#include "IntBinaryTree.h“
void main(void)
{
IntBinaryTree tree;
cout << "Inserting nodes.n";
tree.insertNode(5);
tree.insertNode(8);
tree.insertNode(3);
tree.insertNode(12);
tree.insertNode(9);
28
Program 2 (continued)
cout << "Inorder traversal:n";
tree.showNodesInOrder();
cout << "nPreorder traversal:n";
tree.showNodesPreOrder();
cout << "nPostorder traversal:n";
tree.showNodesPostOrder();
}
29
Program 2 (continued)
Program Output
Inserting nodes.
Inorder traversal:
3
5
8
9
12
Preorder traversal:
5
3
8
12
9
30
Program 2 (continued)
Postorder traversal:
3
9
12
8
5
31
Searching the Tree
The IntBinaryTree class has a public member function,
SearchNode, which returns true if a value is found in the tree, or
false otherwise.
bool IntBinaryTree::searchNode(int num)
{
TreeNode *nodePtr = root;
while (nodePtr)
{
if (nodePtr->value == num)
return true;
else if (num < nodePtr->value)
nodePtr = nodePtr->left;
else
nodePtr = nodePtr->right;
}
return false;
}
32
Program 3
// This program builds a binary tree with 5 nodes.
// The SearchNode function determines if the
// value 3 is in the tree.
#include <iostream.h>
#include "IntBinaryTree.h“
void main(void)
{
IntBinaryTree tree;
cout << "Inserting nodes.n";
tree.insertNode(5);
tree.insertNode(8);
tree.insertNode(3);
tree.insertNode(12);
tree.insertNode(9);
33
Program 3 (continued)
if (tree.searchNode(3))
cout << "3 is found in the tree.n";
else
cout << "3 was not found in the tree.n";
}
Program Output
Inserting nodes.
3 is found in the tree.
34
Deleting a 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 what if we want to delete a node that
has child nodes? We must delete the node
while at the same time preserving the
subtrees that the node links to.
35
Deleting a Node
• 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.
36
Deleting a Node
Figure 6 illustrates a tree in
which we are about to delete a
node with one subtree.
37
Deleting a Node
Figure 7 shows how we will link
the node's subtree with its
parent.
38
Deleting a Node
The problem is not as easily
solved, however, when the
node we are about to delete
has two subtrees. For example,
look at Figure 8.
39
Deleting a Node
• 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 9.
40
Deleting a Node
Figure 9.
41
Deleting a Node
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.
42
The deleteNode Member
Function
void IntBinaryTree::deleteNode(int num, TreeNode *&nodePtr)
{
if (num < nodePtr->value)
deleteNode(num, nodePtr->left);
else if (num > nodePtr->value)
deleteNode(num, nodePtr->right);
else
makeDeletion(nodePtr);
}
Notice the declaration of the nodePtr parameter:
TreeNode *&nodePtr;
nodePtr is not simply a pointer to a TreeNode structure, but a reference to a
pointer to a TreeNode structure. Any action performed on nodePtr is actually
performed on the argument passed into nodePtr.
43
The deleteNode Member
Function
else
makeDeletion(nodePtr);
•The trailing else statement calls the makeDeletion function,
passing nodePtr as its argument.
•The makeDeletion function actually deletes the node from the
tree, and must reattach the deleted node’s subtrees.
•Therefore, it must have access to the actual pointer in the binary tree
to the node that is being deleted.
•This is why the nodePtr parameter in the deleteNode function
is a reference.
44
The makeDeletion Member
Function
void IntBinaryTree::makeDeletion(TreeNode *&nodePtr)
{
TreeNode *tempNodePtr; // Temporary pointer, used in
// reattaching the left subtree.
if (nodePtr == NULL)
cout << "Cannot delete empty node.n";
else if (nodePtr->right == NULL)
{
tempNodePtr = nodePtr;
nodePtr = nodePtr->left; // Reattach the left child
delete tempNodePtr;
}
else if (nodePtr->left == NULL)
{
tempNodePtr = nodePtr;
nodePtr = nodePtr->right; // Reattach the right child
delete tempNodePtr;
}
45
The makeDeletion Member
Function (continued)
// If the node has two children.
else
{
// Move one node the right.
tempNodePtr = nodePtr->right;
// Go to the end left node.
while (tempNodePtr->left)
tempNodePtr = tempNodePtr->left;
// Reattach the left subtree.
tempNodePtr->left = nodePtr->left;
tempNodePtr = nodePtr;
// Reattach the right subtree.
nodePtr = nodePtr->right;
delete tempNodePtr;
}
}
46
Program 4
// This program builds a binary tree with 5 nodes.
// The DeleteNode function is used to remove two
// of them.
#include <iostream.h>
#include "IntBinaryTree.h“
void main(void)
{
IntBinaryTree tree;
cout << "Inserting nodes.n";
tree.insertNode(5);
tree.insertNode(8);
tree.insertNode(3);
tree.insertNode(12);
tree.insertNode(9);
cout << "Here are the values in the tree:n";
tree.showNodesInOrder();
47
Program 4 (continued)
cout << "Deleting 8...n";
tree.remove(8);
cout << "Deleting 12...n";
tree.remove(12);
cout << "Now, here are the nodes:n";
tree.showNodesInOrder();
}
48
Program 4 (continued)
Program Output
Inserting nodes.
Here are the values in the tree:
3
5
8
9
12
Deleting 8...
Deleting 12...
Now, here are the nodes:
3
5
9
49
Template Considerations for
Binary Trees
• When designing your template, remember
that any data types stored in the binary tree
must support the <, >, and == operators.
• If you use the tree to store class objects,
these operators must be overridden.

More Related Content

What's hot

Linked stacks and queues
Linked stacks and queuesLinked stacks and queues
Linked stacks and queuesRamzi Alqrainy
 
358 33 powerpoint-slides_11-efficient-binary-trees_chapter-11
358 33 powerpoint-slides_11-efficient-binary-trees_chapter-11358 33 powerpoint-slides_11-efficient-binary-trees_chapter-11
358 33 powerpoint-slides_11-efficient-binary-trees_chapter-11sumitbardhan
 
linked lists in data structures
linked lists in data structureslinked lists in data structures
linked lists in data structuresDurgaDeviCbit
 
Arrays in Data Structure and Algorithm
Arrays in Data Structure and Algorithm Arrays in Data Structure and Algorithm
Arrays in Data Structure and Algorithm KristinaBorooah
 
BINARY TREE REPRESENTATION.ppt
BINARY TREE REPRESENTATION.pptBINARY TREE REPRESENTATION.ppt
BINARY TREE REPRESENTATION.pptSeethaDinesh
 
Array data structure
Array data structureArray data structure
Array data structuremaamir farooq
 
Double Linked List (Algorithm)
Double Linked List (Algorithm)Double Linked List (Algorithm)
Double Linked List (Algorithm)Huba Akhtar
 
trees in data structure
trees in data structure trees in data structure
trees in data structure shameen khan
 
Binary Tree in Data Structure
Binary Tree in Data StructureBinary Tree in Data Structure
Binary Tree in Data StructureMeghaj Mallick
 
1.1 binary tree
1.1 binary tree1.1 binary tree
1.1 binary treeKrish_ver2
 
Introduction to data structure ppt
Introduction to data structure pptIntroduction to data structure ppt
Introduction to data structure pptNalinNishant3
 

What's hot (20)

Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
 
Linked list
Linked listLinked list
Linked list
 
Linked stacks and queues
Linked stacks and queuesLinked stacks and queues
Linked stacks and queues
 
Graph traversals in Data Structures
Graph traversals in Data StructuresGraph traversals in Data Structures
Graph traversals in Data Structures
 
358 33 powerpoint-slides_11-efficient-binary-trees_chapter-11
358 33 powerpoint-slides_11-efficient-binary-trees_chapter-11358 33 powerpoint-slides_11-efficient-binary-trees_chapter-11
358 33 powerpoint-slides_11-efficient-binary-trees_chapter-11
 
Arrays
ArraysArrays
Arrays
 
Graph data structure and algorithms
Graph data structure and algorithmsGraph data structure and algorithms
Graph data structure and algorithms
 
linked lists in data structures
linked lists in data structureslinked lists in data structures
linked lists in data structures
 
Arrays in Data Structure and Algorithm
Arrays in Data Structure and Algorithm Arrays in Data Structure and Algorithm
Arrays in Data Structure and Algorithm
 
Tree and Binary Search tree
Tree and Binary Search treeTree and Binary Search tree
Tree and Binary Search tree
 
Abstract Data Types
Abstract Data TypesAbstract Data Types
Abstract Data Types
 
BINARY TREE REPRESENTATION.ppt
BINARY TREE REPRESENTATION.pptBINARY TREE REPRESENTATION.ppt
BINARY TREE REPRESENTATION.ppt
 
Array data structure
Array data structureArray data structure
Array data structure
 
Data structures using c
Data structures using cData structures using c
Data structures using c
 
Double Linked List (Algorithm)
Double Linked List (Algorithm)Double Linked List (Algorithm)
Double Linked List (Algorithm)
 
Stacks and Queue - Data Structures
Stacks and Queue - Data StructuresStacks and Queue - Data Structures
Stacks and Queue - Data Structures
 
trees in data structure
trees in data structure trees in data structure
trees in data structure
 
Binary Tree in Data Structure
Binary Tree in Data StructureBinary Tree in Data Structure
Binary Tree in Data Structure
 
1.1 binary tree
1.1 binary tree1.1 binary tree
1.1 binary tree
 
Introduction to data structure ppt
Introduction to data structure pptIntroduction to data structure ppt
Introduction to data structure ppt
 

Viewers also liked

UNIDAD I - INTRODUCCIÓN A LAS TICS - 6
UNIDAD I - INTRODUCCIÓN A LAS TICS - 6UNIDAD I - INTRODUCCIÓN A LAS TICS - 6
UNIDAD I - INTRODUCCIÓN A LAS TICS - 6ElviJE
 
Tata cara perijinan pendakian g
Tata cara perijinan pendakian gTata cara perijinan pendakian g
Tata cara perijinan pendakian gUlfann
 
SCHOOL OF ISLAMIS LEGAL TAUGHT (MAZHAB AS-SYAFIE)
SCHOOL OF ISLAMIS LEGAL TAUGHT (MAZHAB AS-SYAFIE)SCHOOL OF ISLAMIS LEGAL TAUGHT (MAZHAB AS-SYAFIE)
SCHOOL OF ISLAMIS LEGAL TAUGHT (MAZHAB AS-SYAFIE)Ahmad Farhan
 
UNIDAD I - INTRODUCCIÓN A LAS TICS - 6
UNIDAD I - INTRODUCCIÓN A LAS TICS - 6UNIDAD I - INTRODUCCIÓN A LAS TICS - 6
UNIDAD I - INTRODUCCIÓN A LAS TICS - 6ElviJE
 
Mi 103 linked list
Mi 103 linked listMi 103 linked list
Mi 103 linked listAmit Vats
 
Stacks and queue
Stacks and queueStacks and queue
Stacks and queueAmit Vats
 
Rpp 1 huruf hijaiyah
Rpp 1 huruf hijaiyahRpp 1 huruf hijaiyah
Rpp 1 huruf hijaiyahmyob ids
 
Social Media Best Practices For Luxury Brands
Social Media Best Practices For Luxury BrandsSocial Media Best Practices For Luxury Brands
Social Media Best Practices For Luxury BrandsBLACKSTONE DIGITAL AGENCY
 
Hacking the Web
Hacking the WebHacking the Web
Hacking the WebMike Crabb
 
A Beginners Guide to noSQL
A Beginners Guide to noSQLA Beginners Guide to noSQL
A Beginners Guide to noSQLMike Crabb
 

Viewers also liked (12)

UNIDAD I - INTRODUCCIÓN A LAS TICS - 6
UNIDAD I - INTRODUCCIÓN A LAS TICS - 6UNIDAD I - INTRODUCCIÓN A LAS TICS - 6
UNIDAD I - INTRODUCCIÓN A LAS TICS - 6
 
List
ListList
List
 
Tata cara perijinan pendakian g
Tata cara perijinan pendakian gTata cara perijinan pendakian g
Tata cara perijinan pendakian g
 
SCHOOL OF ISLAMIS LEGAL TAUGHT (MAZHAB AS-SYAFIE)
SCHOOL OF ISLAMIS LEGAL TAUGHT (MAZHAB AS-SYAFIE)SCHOOL OF ISLAMIS LEGAL TAUGHT (MAZHAB AS-SYAFIE)
SCHOOL OF ISLAMIS LEGAL TAUGHT (MAZHAB AS-SYAFIE)
 
UNIDAD I - INTRODUCCIÓN A LAS TICS - 6
UNIDAD I - INTRODUCCIÓN A LAS TICS - 6UNIDAD I - INTRODUCCIÓN A LAS TICS - 6
UNIDAD I - INTRODUCCIÓN A LAS TICS - 6
 
Handling
HandlingHandling
Handling
 
Mi 103 linked list
Mi 103 linked listMi 103 linked list
Mi 103 linked list
 
Stacks and queue
Stacks and queueStacks and queue
Stacks and queue
 
Rpp 1 huruf hijaiyah
Rpp 1 huruf hijaiyahRpp 1 huruf hijaiyah
Rpp 1 huruf hijaiyah
 
Social Media Best Practices For Luxury Brands
Social Media Best Practices For Luxury BrandsSocial Media Best Practices For Luxury Brands
Social Media Best Practices For Luxury Brands
 
Hacking the Web
Hacking the WebHacking the Web
Hacking the Web
 
A Beginners Guide to noSQL
A Beginners Guide to noSQLA Beginners Guide to noSQL
A Beginners Guide to noSQL
 

Similar to Binary Trees: Data Structure and Common Operations

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
 
Binary Search Tree
Binary Search TreeBinary Search Tree
Binary Search TreeINAM352782
 
Trees in data structure
Trees in data structureTrees in data structure
Trees in data structureAnusruti Mitra
 
Tree Data Structure by Daniyal Khan
Tree Data Structure by Daniyal KhanTree Data Structure by Daniyal Khan
Tree Data Structure by Daniyal KhanDaniyal Khan
 
Part 1 Your tasks for this assignment are the following1. Disc.docx
Part 1 Your tasks for this assignment are the following1. Disc.docxPart 1 Your tasks for this assignment are the following1. Disc.docx
Part 1 Your tasks for this assignment are the following1. Disc.docxherbertwilson5999
 
VCE Unit 05.pptx
VCE Unit 05.pptxVCE Unit 05.pptx
VCE Unit 05.pptxskilljiolms
 
Binary Search Tree (BST)
Binary Search Tree (BST)Binary Search Tree (BST)
Binary Search Tree (BST)M Sajid R
 
Binary Search Tree
Binary Search TreeBinary Search Tree
Binary Search Treesagar yadav
 
Biary search Tree.docx
Biary search Tree.docxBiary search Tree.docx
Biary search Tree.docxsowmya koneru
 
Binary search tree operations
Binary search tree operationsBinary search tree operations
Binary search tree operationsKamran Zafar
 
Binary tree and operations
Binary tree and operations Binary tree and operations
Binary tree and operations varagilavanya
 
1.2 operations of tree representations
1.2 operations of tree representations 1.2 operations of tree representations
1.2 operations of tree representations Krish_ver2
 

Similar to Binary Trees: Data Structure and Common Operations (20)

Binary tree
Binary treeBinary tree
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 Search Tree
Binary Search TreeBinary Search Tree
Binary Search Tree
 
Binary Search Tree
Binary Search TreeBinary Search Tree
Binary Search Tree
 
DAA PPT.pptx
DAA PPT.pptxDAA PPT.pptx
DAA PPT.pptx
 
Trees in data structure
Trees in data structureTrees in data structure
Trees in data structure
 
Tree Data Structure by Daniyal Khan
Tree Data Structure by Daniyal KhanTree Data Structure by Daniyal Khan
Tree Data Structure by Daniyal Khan
 
Part 1 Your tasks for this assignment are the following1. Disc.docx
Part 1 Your tasks for this assignment are the following1. Disc.docxPart 1 Your tasks for this assignment are the following1. Disc.docx
Part 1 Your tasks for this assignment are the following1. Disc.docx
 
VCE Unit 05.pptx
VCE Unit 05.pptxVCE Unit 05.pptx
VCE Unit 05.pptx
 
Binary tree
Binary tree Binary tree
Binary tree
 
Binary Search Tree (BST)
Binary Search Tree (BST)Binary Search Tree (BST)
Binary Search Tree (BST)
 
Binary Search Tree
Binary Search TreeBinary Search Tree
Binary Search Tree
 
Trees
TreesTrees
Trees
 
Unit iv data structure-converted
Unit  iv data structure-convertedUnit  iv data structure-converted
Unit iv data structure-converted
 
Biary search Tree.docx
Biary search Tree.docxBiary search Tree.docx
Biary search Tree.docx
 
Threaded Binary Tree.pptx
Threaded Binary Tree.pptxThreaded Binary Tree.pptx
Threaded Binary Tree.pptx
 
Binary tree
Binary treeBinary tree
Binary tree
 
Binary search tree operations
Binary search tree operationsBinary search tree operations
Binary search tree operations
 
Binary tree and operations
Binary tree and operations Binary tree and operations
Binary tree and operations
 
1.2 operations of tree representations
1.2 operations of tree representations 1.2 operations of tree representations
1.2 operations of tree representations
 

Recently uploaded

Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...VICTOR MAESTRE RAMIREZ
 
Churning of Butter, Factors affecting .
Churning of Butter, Factors affecting  .Churning of Butter, Factors affecting  .
Churning of Butter, Factors affecting .Satyam Kumar
 
SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )Tsuyoshi Horigome
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024hassan khalil
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile servicerehmti665
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxJoão Esperancinha
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.eptoze12
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVRajaP95
 
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort servicejennyeacort
 
HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2RajaP95
 
chaitra-1.pptx fake news detection using machine learning
chaitra-1.pptx  fake news detection using machine learningchaitra-1.pptx  fake news detection using machine learning
chaitra-1.pptx fake news detection using machine learningmisbanausheenparvam
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxpurnimasatapathy1234
 
Heart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxHeart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxPoojaBan
 
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEINFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEroselinkalist12
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidNikhilNagaraju
 
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...VICTOR MAESTRE RAMIREZ
 
Internship report on mechanical engineering
Internship report on mechanical engineeringInternship report on mechanical engineering
Internship report on mechanical engineeringmalavadedarshan25
 

Recently uploaded (20)

Design and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdfDesign and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdf
 
Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...
 
Churning of Butter, Factors affecting .
Churning of Butter, Factors affecting  .Churning of Butter, Factors affecting  .
Churning of Butter, Factors affecting .
 
SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile service
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
 
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Serviceyoung call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
 
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
 
HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2
 
chaitra-1.pptx fake news detection using machine learning
chaitra-1.pptx  fake news detection using machine learningchaitra-1.pptx  fake news detection using machine learning
chaitra-1.pptx fake news detection using machine learning
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptx
 
Heart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxHeart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptx
 
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEINFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfid
 
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCRCall Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
 
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
 
Internship report on mechanical engineering
Internship report on mechanical engineeringInternship report on mechanical engineering
Internship report on mechanical engineering
 

Binary Trees: Data Structure and Common Operations

  • 2. 2 Definition and Applications of Binary Trees • A binary tree is a non-linear linked list where each node may point to two other nodes.
  • 3. 3 Definition and Applications of Binary Trees • It is anchored at the top by a tree pointer, which is like the head pointer in a linked list. • The first node in the list is called the root node. • The root node has pointers to two other nodes, which are called children, or child nodes.
  • 4. 4 Definition and Applications of Binary Trees • A node that has no children is called a leaf node. • All pointers that do not point to a node are set to NULL.
  • 5. 5 Definition and Applications of Binary Trees • Binary trees can be divided into subtrees. A subtree is an entire branch of the tree, from one particular node down.
  • 6. 6 Definition and Applications of Binary Trees • Binary trees are excellent data structures for searching large amounts of information. They are commonly used in database applications to organize key values that index database records. • When used to facilitate searches, a binary tree is called a binary search tree.
  • 7. 7 Definition and Applications of Binary Trees • Information is stored in binary search trees in a way that makes a binary search simple. For example, look at Figure 3. Values are stored in a binary tree so that a node's left child holds data whose value is less than the node's data, and the node's right child holds data whose value is greater tan the node's data.
  • 8. 8 Definition and Applications of Binary Trees • It is also true that all the nodes to the left of a node hold values less than the node's value. Likewise, all the nodes to the right of a node hold values that are greater than the node's data. • When an application is searching a binary tree, it starts at the root node. If the root node does not hold the search value, the application branches either to the left or right child, depending on whether the search value is less than or grater than the value at the root node.
  • 9. 9 Definition and Applications of Binary Trees • This process continues until the value is found. Figure 4 illustrates the search pattern for finding the value P in the binary tree.
  • 10. 10 Binary Search Tree Operations • Creating a Node: We will demonstrate binary tree operations using the IntBinaryTree class. • The basis of our binary tree node is the following struct declaration: struct TreeNode { int value; TreeNode *left; TreeNode *right; }; • The struct is implemented in the class shown next…
  • 11. 11 IntBinaryTree.h class IntBinaryTree { public: struct TreeNode { int value; TreeNode *left; TreeNode *right; }; TreeNode *root; void destroySubTree(TreeNode *); void deleteNode(int, TreeNode *&); void makeDeletion(TreeNode *&); void displayInOrder(TreeNode *); void displayPreOrder(TreeNode *); void displayPostOrder(TreeNode *);
  • 12. 12 IntBinaryTree.h (continued) public: IntBinaryTree() // Constructor { root = NULL; } ~IntBinaryTree() // Destructor { destroySubTree(root); } void insertNode(int); bool searchNode(int); void remove(int); void showNodesInOrder(void) { displayInOrder(root); } void showNodesPreOrder() { displayPreOrder(root); } void showNodesPostOrder() { displayPostOrder(root); } };
  • 13. 13 Binary Search Tree Operations • Inserting a Node:First, a new node is allocated and its value member is initialized with the new value. • The left and right child pointers are set to NULL, because all nodes must be inserted as leaf nodes. • Next, we determine if the tree is empty. If so, we simply make root point to it, and there is nothing else to be done. But, if there are nodes in the tree, we must find the new node's proper insertion point.
  • 14. 14 Binary Search Tree Operations • If the new value is less than the root node's value, we know it will be inserted somewhere in the left subtree. Otherwise, the value will be inserted into the right subtree. • We simply traverse the subtree, comparing each node along the way with the new node's value, and deciding if we should continue to the left or the right. • When we reach a child pointer that is set to NULL, we have found out insertion point.
  • 15. 15 The insertNode Member Function void IntBinaryTree::insertNode(int num) { TreeNode *newNode, // Pointer to a new node *nodePtr; // Pointer to traverse the tree // Create a new node newNode = new TreeNode; newNode->value = num; newNode->left = newNode->right = NULL; if (!root) // Is the tree empty? root = newNode; else { nodePtr = root;
  • 16. 16 The insertNode Member Function while (nodePtr != NULL) { if (num < nodePtr->value) { if (nodePtr->left) nodePtr = nodePtr->left; else { nodePtr->left = newNode; break; } }
  • 17. 17 The insertNode Member Function else if (num > nodePtr->value) { if (nodePtr->right) nodePtr = nodePtr->right; else { nodePtr->right = newNode; break; } } else { cout << "Duplicate value found in tree.n"; break; } } } }
  • 18. 18 Program 1 // This program builds a binary tree with 5 nodes. #include <iostream.h> #include "IntBinaryTree.h“ void main(void) { IntBinaryTree tree; cout << "Inserting nodes. "; tree.insertNode(5); tree.insertNode(8); tree.insertNode(3); tree.insertNode(12); tree.insertNode(9); cout << "Done.n"; }
  • 19. 19 Program 1 Figure 5 shows the structure of the binary tree built by the program. Note: The shape of the tree is determined by the order in which the values are inserted. The root node in the diagram above holds the value 5 because that was the first value inserted.
  • 20. 20 Traversing the Tree • There are three common methods for traversing a binary tree and processing the value of each node: – inorder – preorder – postorder • Each of these methods is best implemented as a recursive function.
  • 21. 21 Inorder Traversal 1. The node’s left subtree is traversed. 2. The node’s data is processed. 3. The node’s right subtree is traversed.
  • 22. 22 Preorder Traversal 1. The node’s data is processed. 2. The node’s left subtree is traversed. 3. The node’s right subtree is traversed.
  • 23. 23 Postorder Traversal 1. The node’s left subtree is traversed. 2. The node’s right subtree is traversed. 3. The node’s data is processed.
  • 24. 24 The displayInOrder Member Function void IntBinaryTree::displayInOrder(TreeNode *nodePtr) { if (nodePtr) { displayInOrder(nodePtr->left); cout << nodePtr->value << endl; displayInOrder(nodePtr->right); } }
  • 25. 25 The displayPreOrder Member Function void IntBinaryTree::displayPreOrder(TreeNode *nodePtr) { if (nodePtr) { cout << nodePtr->value << endl; displayPreOrder(nodePtr->left); displayPreOrder(nodePtr->right); } }
  • 26. 26 The displayPostOrder Member Function void IntBinaryTree::displayPostOrder(TreeNode *nodePtr) { if (nodePtr) { displayPostOrder(nodePtr->left); displayPostOrder(nodePtr->right); cout << nodePtr->value << endl; } }
  • 27. 27 Program 2 // This program builds a binary tree with 5 nodes. // The nodes are displayed with inorder, preorder, // and postorder algorithms. #include <iostream.h> #include "IntBinaryTree.h“ void main(void) { IntBinaryTree tree; cout << "Inserting nodes.n"; tree.insertNode(5); tree.insertNode(8); tree.insertNode(3); tree.insertNode(12); tree.insertNode(9);
  • 28. 28 Program 2 (continued) cout << "Inorder traversal:n"; tree.showNodesInOrder(); cout << "nPreorder traversal:n"; tree.showNodesPreOrder(); cout << "nPostorder traversal:n"; tree.showNodesPostOrder(); }
  • 29. 29 Program 2 (continued) Program Output Inserting nodes. Inorder traversal: 3 5 8 9 12 Preorder traversal: 5 3 8 12 9
  • 30. 30 Program 2 (continued) Postorder traversal: 3 9 12 8 5
  • 31. 31 Searching the Tree The IntBinaryTree class has a public member function, SearchNode, which returns true if a value is found in the tree, or false otherwise. bool IntBinaryTree::searchNode(int num) { TreeNode *nodePtr = root; while (nodePtr) { if (nodePtr->value == num) return true; else if (num < nodePtr->value) nodePtr = nodePtr->left; else nodePtr = nodePtr->right; } return false; }
  • 32. 32 Program 3 // This program builds a binary tree with 5 nodes. // The SearchNode function determines if the // value 3 is in the tree. #include <iostream.h> #include "IntBinaryTree.h“ void main(void) { IntBinaryTree tree; cout << "Inserting nodes.n"; tree.insertNode(5); tree.insertNode(8); tree.insertNode(3); tree.insertNode(12); tree.insertNode(9);
  • 33. 33 Program 3 (continued) if (tree.searchNode(3)) cout << "3 is found in the tree.n"; else cout << "3 was not found in the tree.n"; } Program Output Inserting nodes. 3 is found in the tree.
  • 34. 34 Deleting a 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 what if we want to delete a node that has child nodes? We must delete the node while at the same time preserving the subtrees that the node links to.
  • 35. 35 Deleting a Node • 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.
  • 36. 36 Deleting a Node Figure 6 illustrates a tree in which we are about to delete a node with one subtree.
  • 37. 37 Deleting a Node Figure 7 shows how we will link the node's subtree with its parent.
  • 38. 38 Deleting a Node The problem is not as easily solved, however, when the node we are about to delete has two subtrees. For example, look at Figure 8.
  • 39. 39 Deleting a Node • 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 9.
  • 41. 41 Deleting a Node 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.
  • 42. 42 The deleteNode Member Function void IntBinaryTree::deleteNode(int num, TreeNode *&nodePtr) { if (num < nodePtr->value) deleteNode(num, nodePtr->left); else if (num > nodePtr->value) deleteNode(num, nodePtr->right); else makeDeletion(nodePtr); } Notice the declaration of the nodePtr parameter: TreeNode *&nodePtr; nodePtr is not simply a pointer to a TreeNode structure, but a reference to a pointer to a TreeNode structure. Any action performed on nodePtr is actually performed on the argument passed into nodePtr.
  • 43. 43 The deleteNode Member Function else makeDeletion(nodePtr); •The trailing else statement calls the makeDeletion function, passing nodePtr as its argument. •The makeDeletion function actually deletes the node from the tree, and must reattach the deleted node’s subtrees. •Therefore, it must have access to the actual pointer in the binary tree to the node that is being deleted. •This is why the nodePtr parameter in the deleteNode function is a reference.
  • 44. 44 The makeDeletion Member Function void IntBinaryTree::makeDeletion(TreeNode *&nodePtr) { TreeNode *tempNodePtr; // Temporary pointer, used in // reattaching the left subtree. if (nodePtr == NULL) cout << "Cannot delete empty node.n"; else if (nodePtr->right == NULL) { tempNodePtr = nodePtr; nodePtr = nodePtr->left; // Reattach the left child delete tempNodePtr; } else if (nodePtr->left == NULL) { tempNodePtr = nodePtr; nodePtr = nodePtr->right; // Reattach the right child delete tempNodePtr; }
  • 45. 45 The makeDeletion Member Function (continued) // If the node has two children. else { // Move one node the right. tempNodePtr = nodePtr->right; // Go to the end left node. while (tempNodePtr->left) tempNodePtr = tempNodePtr->left; // Reattach the left subtree. tempNodePtr->left = nodePtr->left; tempNodePtr = nodePtr; // Reattach the right subtree. nodePtr = nodePtr->right; delete tempNodePtr; } }
  • 46. 46 Program 4 // This program builds a binary tree with 5 nodes. // The DeleteNode function is used to remove two // of them. #include <iostream.h> #include "IntBinaryTree.h“ void main(void) { IntBinaryTree tree; cout << "Inserting nodes.n"; tree.insertNode(5); tree.insertNode(8); tree.insertNode(3); tree.insertNode(12); tree.insertNode(9); cout << "Here are the values in the tree:n"; tree.showNodesInOrder();
  • 47. 47 Program 4 (continued) cout << "Deleting 8...n"; tree.remove(8); cout << "Deleting 12...n"; tree.remove(12); cout << "Now, here are the nodes:n"; tree.showNodesInOrder(); }
  • 48. 48 Program 4 (continued) Program Output Inserting nodes. Here are the values in the tree: 3 5 8 9 12 Deleting 8... Deleting 12... Now, here are the nodes: 3 5 9
  • 49. 49 Template Considerations for Binary Trees • When designing your template, remember that any data types stored in the binary tree must support the <, >, and == operators. • If you use the tree to store class objects, these operators must be overridden.