SlideShare a Scribd company logo
1 of 4
Download to read offline
http://www.tutorialspoint.com/data_structures_algorithms/tree_data_structure.htm Copyright © tutorialspoint.com
DATA STRUCTURE - TREEDATA STRUCTURE - TREE
Tree represents nodes connected by edges. We'll going to discuss binary tree or binary search
tree specifically.
Binary Tree is a special datastructure used for data storage purposes. A binary tree has a special
condition that each node can have two children at maximum. A binary tree have benefits of both
an ordered array and a linked list as search is as quick as in sorted array and insertion or deletion
operation are as fast as in linked list.
Terms
Following are important terms with respect to tree.
Path − Path refers to sequence of nodes along the edges of a tree.
Root − Node at the top of the tree is called root. There is only one root per tree and one
path from root node to any node.
Parent − Any node except root node has one edge upward to a node called parent.
Child − Node below a given node connected by its edge downward is called its child node.
Leaf − Node which does not have any child node is called leaf node.
Subtree − Subtree represents descendents of a node.
Visiting − Visiting refers to checking value of a node when control is on the node.
Traversing − Traversing means passing through nodes in a specific order.
Levels − Level of a node represents the generation of a node. If root node is at level 0, then
its next child node is at level 1, its grandchild is at level 2 and so on.
keys − Key represents a value of a node based on which a search operation is to be carried
out for a node.
Binary Search Tree Representation
Binary Search tree exhibits a special behaviour. A node's left child must have value less than its
parent's value and node's right child must have value greater than it's parent value.
We're going to implement tree using node object and connecting them through references.
Node
A tree node should look like the below structure. It has data part and references to its left and right
child nodes.
struct node {
int data;
struct node *leftChild;
struct node *rightChild;
};
In a tree, all nodes share common construct.
BST Basic Operations
The basic operations that can be performed on binary search tree data structure, are following −
Insert − insert an element in a tree / create a tree.
Search − search an element in a tree.
Preorder Traversal − traverse a tree in a preorder manner.
Inorder Traversal − traverse a tree in an inorder manner.
Postorder Traversal − traverse a tree in a postorder manner.
We shall learn creating insertinginto tree structure and searching a data-item in a tree in this
chapter. We shall learn about tree traversing methods in the coming one.
Insert Operation
The very first insertion creates the tree. Afterwards, whenever an element is to be inserted. First
locate its proper location. Start search from root node then if data is less than key value, search
empty location in left subtree and insert the data. Otherwise search empty location in right subtree
and insert the data.
Algorithm
If root is NULL
then create root node
return
If root exists then
compare the data with node.data
while until insertion position is located
If data is greater than node.data
goto right subtree
else
goto left subtree
endwhile
insert data
end If
Implementation
The implementation of insert function should look like this −
void insert(int data) {
struct node *tempNode = (struct node*) malloc(sizeof(struct node));
struct node *current;
struct node *parent;
tempNode->data = data;
tempNode->leftChild = NULL;
tempNode->rightChild = NULL;
//if tree is empty, create root node
if(root == NULL) {
root = tempNode;
}else {
current = root;
parent = NULL;
while(1) {
parent = current;
//go to left of the tree
if(data < parent->data) {
current = current->leftChild;
//insert to the left
if(current == NULL) {
parent->leftChild = tempNode;
return;
}
}
//go to right of the tree
else {
current = current->rightChild;
//insert to the right
if(current == NULL) {
parent->rightChild = tempNode;
return;
}
}
}
}
}
Search Operation
Whenever an element is to be search. Start search from root node then if data is less than key
value, search element in left subtree otherwise search element in right subtree. Follow the same
algorithm for each node.
Algorithm
If root.data is equal to search.data
return root
else
while data not found
If data is greater than node.data
goto right subtree
else
goto left subtree
If data found
return node
endwhile
return data not found
end if
The implementation of this algorithm should look like this.
struct node* search(int data) {
struct node *current = root;
printf("Visiting elements: ");
while(current->data != data) {
if(current != NULL)
printf("%d ",current->data);
//go to left tree
if(current->data > data) {
current = current->leftChild;
}
//else go to right tree
else {
current = current->rightChild;
}
//not found
if(current == NULL) {
return NULL;
}
return current;
}
}
To see the implementation of binary search tree data structure, please click here.
Loading [MathJax]/jax/output/HTML-CSS/jax.js

More Related Content

What's hot

Elementary data organisation
Elementary data organisationElementary data organisation
Elementary data organisation
Muzamil Hussain
 

What's hot (20)

Data structures
Data structuresData structures
Data structures
 
Elementary data organisation
Elementary data organisationElementary data organisation
Elementary data organisation
 
introduction to Data Structure and classification
 introduction to Data Structure and classification introduction to Data Structure and classification
introduction to Data Structure and classification
 
1.1 binary tree
1.1 binary tree1.1 binary tree
1.1 binary tree
 
Data Structure # vpmp polytechnic
Data Structure # vpmp polytechnicData Structure # vpmp polytechnic
Data Structure # vpmp polytechnic
 
Chapter 1( intro &amp; overview)
Chapter 1( intro &amp; overview)Chapter 1( intro &amp; overview)
Chapter 1( intro &amp; overview)
 
Binary search tree
Binary search treeBinary search tree
Binary search tree
 
Types Of Data Structure
Types Of Data StructureTypes Of Data Structure
Types Of Data Structure
 
Basics of data structure
Basics of data structureBasics of data structure
Basics of data structure
 
Binary tree
Binary tree Binary tree
Binary tree
 
Introduction of Data Structure
Introduction of Data StructureIntroduction of Data Structure
Introduction of Data Structure
 
Binary trees
Binary treesBinary trees
Binary trees
 
Data Structures - Lecture 2 [Introduction to Data Structures]
Data Structures - Lecture 2 [Introduction to Data Structures]Data Structures - Lecture 2 [Introduction to Data Structures]
Data Structures - Lecture 2 [Introduction to Data Structures]
 
Mca ii dfs u-1 introduction to data structure
Mca ii dfs u-1 introduction to data structureMca ii dfs u-1 introduction to data structure
Mca ii dfs u-1 introduction to data structure
 
Introduction to data structure
Introduction to data structureIntroduction to data structure
Introduction to data structure
 
Introduction to stack
Introduction to stack Introduction to stack
Introduction to stack
 
Binary Tree in Data Structure
Binary Tree in Data StructureBinary Tree in Data Structure
Binary Tree in Data Structure
 
Files and data storage
Files and data storageFiles and data storage
Files and data storage
 
Data structure
Data structureData structure
Data structure
 
Binary search tree
Binary search treeBinary search tree
Binary search tree
 

Similar to Tree

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
 
Fundamentalsofdatastructures 110501104205-phpapp02
Fundamentalsofdatastructures 110501104205-phpapp02Fundamentalsofdatastructures 110501104205-phpapp02
Fundamentalsofdatastructures 110501104205-phpapp02
Getachew Ganfur
 
Final tree.ppt tells about tree presentation
Final tree.ppt tells about tree presentationFinal tree.ppt tells about tree presentation
Final tree.ppt tells about tree presentation
nakulvarshney371
 
Modeling and Simulation Lesson 3: CHARACTERISTICS of Data Structures.pptx
Modeling and Simulation Lesson 3: CHARACTERISTICS of Data Structures.pptxModeling and Simulation Lesson 3: CHARACTERISTICS of Data Structures.pptx
Modeling and Simulation Lesson 3: CHARACTERISTICS of Data Structures.pptx
Angela Arago
 
Fundamentals of data structures
Fundamentals of data structuresFundamentals of data structures
Fundamentals of data structures
Niraj Agarwal
 

Similar to Tree (20)

Tree Data Structure by Daniyal Khan
Tree Data Structure by Daniyal KhanTree Data Structure by Daniyal Khan
Tree Data Structure by Daniyal Khan
 
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
 
Biary search Tree.docx
Biary search Tree.docxBiary search Tree.docx
Biary search Tree.docx
 
Binary Search Tree
Binary Search TreeBinary Search Tree
Binary Search Tree
 
binarysearchtreeindatastructures-200604055006 (1).pdf
binarysearchtreeindatastructures-200604055006 (1).pdfbinarysearchtreeindatastructures-200604055006 (1).pdf
binarysearchtreeindatastructures-200604055006 (1).pdf
 
UNIT-4 TREES.ppt
UNIT-4 TREES.pptUNIT-4 TREES.ppt
UNIT-4 TREES.ppt
 
Binary tree
Binary treeBinary tree
Binary tree
 
Fundamentalsofdatastructures 110501104205-phpapp02
Fundamentalsofdatastructures 110501104205-phpapp02Fundamentalsofdatastructures 110501104205-phpapp02
Fundamentalsofdatastructures 110501104205-phpapp02
 
Final tree.ppt tells about tree presentation
Final tree.ppt tells about tree presentationFinal tree.ppt tells about tree presentation
Final tree.ppt tells about tree presentation
 
Unit8 C
Unit8 CUnit8 C
Unit8 C
 
linked lists in data structures
linked lists in data structureslinked lists in data structures
linked lists in data structures
 
104333 sri vidhya eng notes
104333 sri vidhya eng notes104333 sri vidhya eng notes
104333 sri vidhya eng notes
 
binarysearch-180319163432.pdf 11111111111
binarysearch-180319163432.pdf 11111111111binarysearch-180319163432.pdf 11111111111
binarysearch-180319163432.pdf 11111111111
 
Modeling and Simulation Lesson 3: CHARACTERISTICS of Data Structures.pptx
Modeling and Simulation Lesson 3: CHARACTERISTICS of Data Structures.pptxModeling and Simulation Lesson 3: CHARACTERISTICS of Data Structures.pptx
Modeling and Simulation Lesson 3: CHARACTERISTICS of Data Structures.pptx
 
Fundamentals of data structures
Fundamentals of data structuresFundamentals of data structures
Fundamentals of data structures
 
VCE Unit 05.pptx
VCE Unit 05.pptxVCE Unit 05.pptx
VCE Unit 05.pptx
 
Trees
TreesTrees
Trees
 
Trees
TreesTrees
Trees
 
Binary trees
Binary treesBinary trees
Binary trees
 
Unit.1 Introduction to Data Structuresres
Unit.1 Introduction to Data StructuresresUnit.1 Introduction to Data Structuresres
Unit.1 Introduction to Data Structuresres
 

More from maamir farooq (20)

Ooad lab1
Ooad lab1Ooad lab1
Ooad lab1
 
Lesson 03
Lesson 03Lesson 03
Lesson 03
 
Lesson 02
Lesson 02Lesson 02
Lesson 02
 
Php client libray
Php client librayPhp client libray
Php client libray
 
Swiftmailer
SwiftmailerSwiftmailer
Swiftmailer
 
Lect15
Lect15Lect15
Lect15
 
Lec 7
Lec 7Lec 7
Lec 7
 
Lec 6
Lec 6Lec 6
Lec 6
 
Lec 5
Lec 5Lec 5
Lec 5
 
J query 1.7 cheat sheet
J query 1.7 cheat sheetJ query 1.7 cheat sheet
J query 1.7 cheat sheet
 
Assignment
AssignmentAssignment
Assignment
 
Java script summary
Java script summaryJava script summary
Java script summary
 
Lec 3
Lec 3Lec 3
Lec 3
 
Lec 2
Lec 2Lec 2
Lec 2
 
Lec 1
Lec 1Lec 1
Lec 1
 
Css summary
Css summaryCss summary
Css summary
 
Manual of image processing lab
Manual of image processing labManual of image processing lab
Manual of image processing lab
 
Session management
Session managementSession management
Session management
 
Data management
Data managementData management
Data management
 
Content provider
Content providerContent provider
Content provider
 

Recently uploaded

Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
kauryashika82
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
ciinovamais
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
PECB
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
negromaestrong
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
Chris Hunter
 
An Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdfAn Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdf
SanaAli374401
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
QucHHunhnh
 
Gardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch LetterGardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch Letter
MateoGardella
 

Recently uploaded (20)

Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
An Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdfAn Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdf
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Gardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch LetterGardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch Letter
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 

Tree

  • 1. http://www.tutorialspoint.com/data_structures_algorithms/tree_data_structure.htm Copyright © tutorialspoint.com DATA STRUCTURE - TREEDATA STRUCTURE - TREE Tree represents nodes connected by edges. We'll going to discuss binary tree or binary search tree specifically. Binary Tree is a special datastructure used for data storage purposes. A binary tree has a special condition that each node can have two children at maximum. A binary tree have benefits of both an ordered array and a linked list as search is as quick as in sorted array and insertion or deletion operation are as fast as in linked list. Terms Following are important terms with respect to tree. Path − Path refers to sequence of nodes along the edges of a tree. Root − Node at the top of the tree is called root. There is only one root per tree and one path from root node to any node. Parent − Any node except root node has one edge upward to a node called parent. Child − Node below a given node connected by its edge downward is called its child node. Leaf − Node which does not have any child node is called leaf node. Subtree − Subtree represents descendents of a node. Visiting − Visiting refers to checking value of a node when control is on the node. Traversing − Traversing means passing through nodes in a specific order. Levels − Level of a node represents the generation of a node. If root node is at level 0, then its next child node is at level 1, its grandchild is at level 2 and so on. keys − Key represents a value of a node based on which a search operation is to be carried out for a node. Binary Search Tree Representation Binary Search tree exhibits a special behaviour. A node's left child must have value less than its
  • 2. parent's value and node's right child must have value greater than it's parent value. We're going to implement tree using node object and connecting them through references. Node A tree node should look like the below structure. It has data part and references to its left and right child nodes. struct node { int data; struct node *leftChild; struct node *rightChild; }; In a tree, all nodes share common construct. BST Basic Operations The basic operations that can be performed on binary search tree data structure, are following − Insert − insert an element in a tree / create a tree. Search − search an element in a tree. Preorder Traversal − traverse a tree in a preorder manner. Inorder Traversal − traverse a tree in an inorder manner. Postorder Traversal − traverse a tree in a postorder manner. We shall learn creating insertinginto tree structure and searching a data-item in a tree in this chapter. We shall learn about tree traversing methods in the coming one. Insert Operation The very first insertion creates the tree. Afterwards, whenever an element is to be inserted. First locate its proper location. Start search from root node then if data is less than key value, search empty location in left subtree and insert the data. Otherwise search empty location in right subtree and insert the data. Algorithm If root is NULL then create root node return If root exists then compare the data with node.data while until insertion position is located If data is greater than node.data goto right subtree else
  • 3. goto left subtree endwhile insert data end If Implementation The implementation of insert function should look like this − void insert(int data) { struct node *tempNode = (struct node*) malloc(sizeof(struct node)); struct node *current; struct node *parent; tempNode->data = data; tempNode->leftChild = NULL; tempNode->rightChild = NULL; //if tree is empty, create root node if(root == NULL) { root = tempNode; }else { current = root; parent = NULL; while(1) { parent = current; //go to left of the tree if(data < parent->data) { current = current->leftChild; //insert to the left if(current == NULL) { parent->leftChild = tempNode; return; } } //go to right of the tree else { current = current->rightChild; //insert to the right if(current == NULL) { parent->rightChild = tempNode; return; } } } } } Search Operation Whenever an element is to be search. Start search from root node then if data is less than key value, search element in left subtree otherwise search element in right subtree. Follow the same algorithm for each node. Algorithm If root.data is equal to search.data return root else
  • 4. while data not found If data is greater than node.data goto right subtree else goto left subtree If data found return node endwhile return data not found end if The implementation of this algorithm should look like this. struct node* search(int data) { struct node *current = root; printf("Visiting elements: "); while(current->data != data) { if(current != NULL) printf("%d ",current->data); //go to left tree if(current->data > data) { current = current->leftChild; } //else go to right tree else { current = current->rightChild; } //not found if(current == NULL) { return NULL; } return current; } } To see the implementation of binary search tree data structure, please click here. Loading [MathJax]/jax/output/HTML-CSS/jax.js