SlideShare a Scribd company logo
Data Structures Using C++ 1
Chapter 11
Binary Trees
Data Structures Using C++ 2
Chapter Objectives
• Learn about binary trees
• Explore various binary tree traversal algorithms
• Learn how to organize data in a binary search tree
• Discover how to insert and delete items in a binary
search tree
• Explore nonrecursive binary tree traversal
algorithms
• Learn about AVL (height-balanced) trees
Data Structures Using C++ 3
Binary Trees
• Definition: A binary tree, T, is either empty
or such that:
– T has a special node called the root node;
– T has two sets of nodes, LT and RT, called the
left subtree and right subtree of T, respectively;
– LT and RT are binary trees
Data Structures Using C++ 4
Binary Tree
Data Structures Using C++ 5
Binary Tree With One Node
The root node of the binary tree = A
LA = empty
RA = empty
Data Structures Using C++ 6
Binary Trees With Two Nodes
Data Structures Using C++ 7
Binary Trees With Two Nodes
Data Structures Using C++ 8
Various Binary Trees With Three
Nodes
Data Structures Using C++ 9
Binary Trees
Following struct defines the node of a binary tree:
template<class elemType>
struct nodeType
{
elemType info;
nodeType<elemType> *llink;
nodeType<elemType> *rlink;
};
Data Structures Using C++ 10
Nodes
• For each node:
– Data is stored in info
– The pointer to the left child is stored in llink
– The pointer to the right child is stored in rlink
Data Structures Using C++ 11
General Binary Tree
Data Structures Using C++ 12
Binary Tree Definitions
• Leaf: node that has no left and right
children
• Parent: node with at least one child node
• Level of a node: number of branches on the
path from root to node
• Height of a binary tree: number of nodes no
the longest path from root to node
Data Structures Using C++ 13
Height of a Binary Tree
Recursive algorithm to find height of binary
tree:
(height(p) denotes height of binary tree with
root p):
if(p is NULL)
height(p) = 0
else
height(p) = 1 + max(height(p->llink), height(p-
>rlink))
Data Structures Using C++ 14
Height of a Binary Tree
Function to implement above algorithm:
template<class elemType>
int height(nodeType<elemType> *p)
{
if(p == NULL)
return 0;
else
return 1 + max(height(p->llink),
height(p->rlink));
}
Data Structures Using C++ 15
Copy Tree
• Useful operation on binary trees is to
make identical copy of binary tree
• Use function copyTree when we
overload assignment operator and
implement copy constructor
Data Structures Using C++ 16
Copy Tree
template<class elemType>
void copyTree(nodeType<elemType>* &copiedTreeRoot,
nodeType<elemType>* otherTreeRoot)
{
if(otherTreeRoot == NULL)
copiedTreeRoot = NULL;
else
{
copiedTreeRoot = new nodeType<elemType>;
copiedTreeRoot->info = otherTreeRoot->info;
copyTree(copiedTreeRoot->llink, otherTreeRoot->llink);
copyTree(copiedTreeRoot->rlink, otherTreeRoot->rlink);
}
}//end copyTree
Data Structures Using C++ 17
Binary Tree Traversal
• Must start with the root, then
– Visit the node first or
– Visit the subtrees first
• Three different traversals
– Inorder
– Preorder
– Postorder
Data Structures Using C++ 18
Traversals
• Inorder
– Traverse the left subtree
– Visit the node
– Traverse the right subtree
• Preorder
– Visit the node
– Traverse the left subtree
– Traverse the right subtree
Data Structures Using C++ 19
Traversals
• Postorder
– Traverse the left subtree
– Traverse the right subtree
– Visit the node
Data Structures Using C++ 20
Binary Tree: Inorder Traversal
Data Structures Using C++ 21
Binary Tree: Inorder Traversal
template<class elemType>
void inorder(nodeType<elemType>
*p)
{
if(p != NULL)
{
inorder(p->llink);
cout<<p->info<<” “;
inorder(p->rlink);
}
}
Data Structures Using C++ 22
Binary Tree: Traversals
template<class elemType>
void preorder(nodeType<elemType> *p)
{
if(p != NULL)
{
cout<<p->info<<” “;
preorder(p->llink);
preorder(p->rlink);
}
}
template<class elemType>
void postorder(nodeType<elemType>
*p)
{
if(p != NULL)
{
postorder(p->llink);
postorder(p->rlink);
cout<<p->info<<” “;
}
}1
Data Structures Using C++ 23
Implementing Binary Trees:
class binaryTreeType Functions
• Public
– isEmpty
– inorderTraversal
– preorderTraversal
– postorderTraversal
– treeHeight
– treeNodeCount
– treeLeavesCount
– destroyTree
• Private
• copyTree
• Destroy
• Inorder, preorder,
postorder
• Height
• Max
• nodeCount
• leavesCount
Data Structures Using C++ 24
Binary Search Trees
• Data in each node
– Larger than the data in its left child
– Smaller than the data in its right child
• A binary search tree,t, is either empty or:
– T has a special node called the root node
– T has two sets of nodes, LT and RT, called the left
subtree and right subtree of T, respectively
– Key in root node larger than every key in left subtree
and smaller than every key in right subtree
– LT and RT are binary search trees
Data Structures Using C++ 25
Binary Search Trees
Data Structures Using C++ 26
Operations Performed on Binary
Search Trees
• Determine whether the binary search tree is
empty
• Search the binary search tree for a particular
item
• Insert an item in the binary search tree
• Delete an item from the binary search tree
Data Structures Using C++ 27
Operations Performed on Binary
Search Trees
• Find the height of the binary search tree
• Find the number of nodes in the binary
search tree
• Find the number of leaves in the binary
search tree
• Traverse the binary search tree
• Copy the binary search tree
Data Structures Using C++ 28
Binary Search Tree Analysis
Worst Case: Linear tree
Data Structures Using C++ 29
Binary Search Tree Analysis
• Theorem: Let T be a binary search tree with n
nodes, where n > 0.The average number of nodes
visited in a search of T is approximately 1.39log2n
• Number of comparisons required to determine
whether x is in T is one more than the number of
comparisons required to insert x in T
• Number of comparisons required to insert x in T
same as the number of comparisons made in
unsuccessful search, reflecting that x is not in T
Data Structures Using C++ 30
Binary Search Tree Analysis
It follows that:
It is also known that:
Solving Equations (11-1) and (11-2)
Data Structures Using C++ 31
Nonrecursive Inorder Traversal
Data Structures Using C++ 32
Nonrecursive Inorder Traversal:
General Algorithm
1. current = root; //start traversing the binary tree at
// the root node
2. while(current is not NULL or stack is nonempty)
if(current is not NULL)
{
push current onto stack;
current = current->llink;
}
else
{
pop stack into current;
visit current; //visit the node
current = current->rlink; //move to the
//right child
}
Data Structures Using C++ 33
Nonrecursive Preorder Traversal:
General Algorithm
1. current = root; //start the traversal at the root node
2. while(current is not NULL or stack is nonempty)
if(current is not NULL)
{
visit current;
push current onto stack;
current = current->llink;
}
else
{
pop stack into current;
current = current->rlink; //prepare to visit
//the right subtree
}
Data Structures Using C++ 34
Nonrecursive Postorder Traversal
1. current = root; //start traversal at root node
2. v = 0;
3. if(current is NULL)
the binary tree is empty
4. if(current is not NULL)
a. push current into stack;
b. push 1 onto stack;
c. current = current->llink;
d. while(stack is not empty)
if(current is not NULL and v is 0)
{
push current and 1 onto stack;
current = current->llink;
}
Data Structures Using C++ 35
Nonrecursive Postorder Traversal
(Continued)
else
{
pop stack into current and v;
if(v == 1)
{
push current and 2 onto stack;
current = current->rlink;
v = 0;
}
else
visit current;
}
Data Structures Using C++ 36
AVL (Height-balanced Trees)
• A perfectly balanced binary tree is a binary
tree such that:
– The height of the left and right subtrees of the
root are equal
– The left and right subtrees of the root are
perfectly balanced binary trees
Data Structures Using C++ 37
Perfectly Balanced Binary Tree
Data Structures Using C++ 38
AVL (Height-balanced Trees)
• An AVL tree (or height-balanced tree) is a
binary search tree such that:
– The height of the left and right subtrees of the
root differ by at most 1
– The left and right subtrees of the root are AVL
trees
Data Structures Using C++ 39
AVL Trees
Data Structures Using C++ 40
Non-AVL Trees
Data Structures Using C++ 41
Insertion Into AVL Tree
Data Structures Using C++ 42
Insertion Into AVL Trees
Data Structures Using C++ 43
Insertion Into AVL Trees
Data Structures Using C++ 44
Insertion Into AVL Trees
Data Structures Using C++ 45
Insertion Into AVL Trees
Data Structures Using C++ 46
AVL Tree Rotations
• Reconstruction procedure: rotating tree
• left rotation and right rotation
• Suppose that the rotation occurs at node x
• Left rotation: certain nodes from the right subtree of x
move to its left subtree; the root of the right subtree of x
becomes the new root of the reconstructed subtree
• Right rotation at x: certain nodes from the left subtree of x
move to its right subtree; the root of the left subtree of x
becomes the new root of the reconstructed subtree
Data Structures Using C++ 47
AVL Tree Rotations
Data Structures Using C++ 48
AVL Tree Rotations
Data Structures Using C++ 49
AVL Tree Rotations
Data Structures Using C++ 50
AVL Tree Rotations
Data Structures Using C++ 51
AVL Tree Rotations
Data Structures Using C++ 52
AVL Tree Rotations
Data Structures Using C++ 53
Deletion From AVL Trees
• Case 1: the node to be deleted is a leaf
• Case 2: the node to be deleted has no right
child, that is, its right subtree is empty
• Case 3: the node to be deleted has no left
child, that is, its left subtree is empty
• Case 4: the node to be deleted has a left
child and a right child
Data Structures Using C++ 54
Analysis: AVL Trees
Consider all the possible AVL trees of height h. Let Th be an
AVL tree of height h such that Th has the fewest number of
nodes. Let Thl denote the left subtree of Th and Thr denote the
right subtree of Th. Then:
where | Th | denotes the number of nodes in Th.
Data Structures Using C++ 55
Analysis: AVL Trees
Suppose that Thl is of height h – 1 and Thr is of height h – 2.
Thl is an AVL tree of height h – 1 such that Thl has the fewest
number of nodes among all AVL trees of height h – 1. Thr is
an AVL tree of height h – 2 that has the fewest number of
nodes among all AVL trees of height h – 2. Thl is of the form
Th -1 and Thr is of the form Th -2. Hence:
Data Structures Using C++ 56
Analysis: AVL Trees
Let Fh+2 = |Th | + 1. Then:
Called a Fibonacci sequence; solution to Fh is given by:
Hence
From this it can be concluded that
Data Structures Using C++ 57
Chapter Summary
• Binary trees
• Binary search trees
• Recursive traversal algorithms
• Nonrecursive traversal algorithms
• AVL trees

More Related Content

Similar to chap11.ppt

9780324782011_PPT_ch09.ppt
9780324782011_PPT_ch09.ppt9780324782011_PPT_ch09.ppt
9780324782011_PPT_ch09.ppt
ValhallaExcalibur
 
lecture10 date structure types of graph and terminology
lecture10 date structure types of graph and terminologylecture10 date structure types of graph and terminology
lecture10 date structure types of graph and terminology
KamranAli649587
 
7.tree
7.tree7.tree
Realtime Analytics
Realtime AnalyticsRealtime Analytics
Realtime Analytics
eXascale Infolab
 
unit06-3-Trees.pdf
unit06-3-Trees.pdfunit06-3-Trees.pdf
unit06-3-Trees.pdf
AnmolYadav509681
 
Tree traversal techniques
Tree traversal techniquesTree traversal techniques
Tree traversal techniques
Syed Zaid Irshad
 
RECURSION.pptx
RECURSION.pptxRECURSION.pptx
RECURSION.pptx
PrestonKhumbula1
 
Fundamentalsofdatastructures 110501104205-phpapp02
Fundamentalsofdatastructures 110501104205-phpapp02Fundamentalsofdatastructures 110501104205-phpapp02
Fundamentalsofdatastructures 110501104205-phpapp02
Getachew Ganfur
 
Introduction to data structure by anil dutt
Introduction to data structure by anil duttIntroduction to data structure by anil dutt
Introduction to data structure by anil dutt
Anil Dutt
 
Q
QQ
Editors l21 l24
Editors l21 l24Editors l21 l24
Editors l21 l24
Neha Pachauri
 
trees-and-graphs_computer_science_for_student.pptx
trees-and-graphs_computer_science_for_student.pptxtrees-and-graphs_computer_science_for_student.pptx
trees-and-graphs_computer_science_for_student.pptx
TanvirAhmed166122
 
Cinterviews Binarysearch Tree
Cinterviews Binarysearch TreeCinterviews Binarysearch Tree
Cinterviews Binarysearch Tree
cinterviews
 
Binary tree and operations
Binary tree and operations Binary tree and operations
Binary tree and operations
varagilavanya
 
Query Compilation in Impala
Query Compilation in ImpalaQuery Compilation in Impala
Query Compilation in Impala
Cloudera, Inc.
 
Unit 2_3 Binary Tree Traversals.pdf
Unit 2_3 Binary Tree Traversals.pdfUnit 2_3 Binary Tree Traversals.pdf
Unit 2_3 Binary Tree Traversals.pdf
KanchanPatil34
 
Data Structures
Data StructuresData Structures
Data Structures
Nitesh Bichwani
 
Chapter 15
Chapter 15Chapter 15
Chapter 15
ashish bansal
 
part4-trees.ppt
part4-trees.pptpart4-trees.ppt
part4-trees.ppt
Suneel61
 
12. Heaps - Data Structures using C++ by Varsha Patil
12. Heaps - Data Structures using C++ by Varsha Patil12. Heaps - Data Structures using C++ by Varsha Patil
12. Heaps - Data Structures using C++ by Varsha Patil
widespreadpromotion
 

Similar to chap11.ppt (20)

9780324782011_PPT_ch09.ppt
9780324782011_PPT_ch09.ppt9780324782011_PPT_ch09.ppt
9780324782011_PPT_ch09.ppt
 
lecture10 date structure types of graph and terminology
lecture10 date structure types of graph and terminologylecture10 date structure types of graph and terminology
lecture10 date structure types of graph and terminology
 
7.tree
7.tree7.tree
7.tree
 
Realtime Analytics
Realtime AnalyticsRealtime Analytics
Realtime Analytics
 
unit06-3-Trees.pdf
unit06-3-Trees.pdfunit06-3-Trees.pdf
unit06-3-Trees.pdf
 
Tree traversal techniques
Tree traversal techniquesTree traversal techniques
Tree traversal techniques
 
RECURSION.pptx
RECURSION.pptxRECURSION.pptx
RECURSION.pptx
 
Fundamentalsofdatastructures 110501104205-phpapp02
Fundamentalsofdatastructures 110501104205-phpapp02Fundamentalsofdatastructures 110501104205-phpapp02
Fundamentalsofdatastructures 110501104205-phpapp02
 
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
 
Q
QQ
Q
 
Editors l21 l24
Editors l21 l24Editors l21 l24
Editors l21 l24
 
trees-and-graphs_computer_science_for_student.pptx
trees-and-graphs_computer_science_for_student.pptxtrees-and-graphs_computer_science_for_student.pptx
trees-and-graphs_computer_science_for_student.pptx
 
Cinterviews Binarysearch Tree
Cinterviews Binarysearch TreeCinterviews Binarysearch Tree
Cinterviews Binarysearch Tree
 
Binary tree and operations
Binary tree and operations Binary tree and operations
Binary tree and operations
 
Query Compilation in Impala
Query Compilation in ImpalaQuery Compilation in Impala
Query Compilation in Impala
 
Unit 2_3 Binary Tree Traversals.pdf
Unit 2_3 Binary Tree Traversals.pdfUnit 2_3 Binary Tree Traversals.pdf
Unit 2_3 Binary Tree Traversals.pdf
 
Data Structures
Data StructuresData Structures
Data Structures
 
Chapter 15
Chapter 15Chapter 15
Chapter 15
 
part4-trees.ppt
part4-trees.pptpart4-trees.ppt
part4-trees.ppt
 
12. Heaps - Data Structures using C++ by Varsha Patil
12. Heaps - Data Structures using C++ by Varsha Patil12. Heaps - Data Structures using C++ by Varsha Patil
12. Heaps - Data Structures using C++ by Varsha Patil
 

Recently uploaded

KuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressionsKuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
Victor Morales
 
14 Template Contractual Notice - EOT Application
14 Template Contractual Notice - EOT Application14 Template Contractual Notice - EOT Application
14 Template Contractual Notice - EOT Application
SyedAbiiAzazi1
 
Harnessing WebAssembly for Real-time Stateless Streaming Pipelines
Harnessing WebAssembly for Real-time Stateless Streaming PipelinesHarnessing WebAssembly for Real-time Stateless Streaming Pipelines
Harnessing WebAssembly for Real-time Stateless Streaming Pipelines
Christina Lin
 
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODELDEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
gerogepatton
 
Low power architecture of logic gates using adiabatic techniques
Low power architecture of logic gates using adiabatic techniquesLow power architecture of logic gates using adiabatic techniques
Low power architecture of logic gates using adiabatic techniques
nooriasukmaningtyas
 
6th International Conference on Machine Learning & Applications (CMLA 2024)
6th International Conference on Machine Learning & Applications (CMLA 2024)6th International Conference on Machine Learning & Applications (CMLA 2024)
6th International Conference on Machine Learning & Applications (CMLA 2024)
ClaraZara1
 
bank management system in java and mysql report1.pdf
bank management system in java and mysql report1.pdfbank management system in java and mysql report1.pdf
bank management system in java and mysql report1.pdf
Divyam548318
 
CSM Cloud Service Management Presentarion
CSM Cloud Service Management PresentarionCSM Cloud Service Management Presentarion
CSM Cloud Service Management Presentarion
rpskprasana
 
International Conference on NLP, Artificial Intelligence, Machine Learning an...
International Conference on NLP, Artificial Intelligence, Machine Learning an...International Conference on NLP, Artificial Intelligence, Machine Learning an...
International Conference on NLP, Artificial Intelligence, Machine Learning an...
gerogepatton
 
ML Based Model for NIDS MSc Updated Presentation.v2.pptx
ML Based Model for NIDS MSc Updated Presentation.v2.pptxML Based Model for NIDS MSc Updated Presentation.v2.pptx
ML Based Model for NIDS MSc Updated Presentation.v2.pptx
JamalHussainArman
 
5214-1693458878915-Unit 6 2023 to 2024 academic year assignment (AutoRecovere...
5214-1693458878915-Unit 6 2023 to 2024 academic year assignment (AutoRecovere...5214-1693458878915-Unit 6 2023 to 2024 academic year assignment (AutoRecovere...
5214-1693458878915-Unit 6 2023 to 2024 academic year assignment (AutoRecovere...
ihlasbinance2003
 
digital fundamental by Thomas L.floydl.pdf
digital fundamental by Thomas L.floydl.pdfdigital fundamental by Thomas L.floydl.pdf
digital fundamental by Thomas L.floydl.pdf
drwaing
 
PPT on GRP pipes manufacturing and testing
PPT on GRP pipes manufacturing and testingPPT on GRP pipes manufacturing and testing
PPT on GRP pipes manufacturing and testing
anoopmanoharan2
 
Recycled Concrete Aggregate in Construction Part III
Recycled Concrete Aggregate in Construction Part IIIRecycled Concrete Aggregate in Construction Part III
Recycled Concrete Aggregate in Construction Part III
Aditya Rajan Patra
 
132/33KV substation case study Presentation
132/33KV substation case study Presentation132/33KV substation case study Presentation
132/33KV substation case study Presentation
kandramariana6
 
Properties Railway Sleepers and Test.pptx
Properties Railway Sleepers and Test.pptxProperties Railway Sleepers and Test.pptx
Properties Railway Sleepers and Test.pptx
MDSABBIROJJAMANPAYEL
 
2. Operations Strategy in a Global Environment.ppt
2. Operations Strategy in a Global Environment.ppt2. Operations Strategy in a Global Environment.ppt
2. Operations Strategy in a Global Environment.ppt
PuktoonEngr
 
Exception Handling notes in java exception
Exception Handling notes in java exceptionException Handling notes in java exception
Exception Handling notes in java exception
Ratnakar Mikkili
 
Question paper of renewable energy sources
Question paper of renewable energy sourcesQuestion paper of renewable energy sources
Question paper of renewable energy sources
mahammadsalmanmech
 
Heat Resistant Concrete Presentation ppt
Heat Resistant Concrete Presentation pptHeat Resistant Concrete Presentation ppt
Heat Resistant Concrete Presentation ppt
mamunhossenbd75
 

Recently uploaded (20)

KuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressionsKuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
 
14 Template Contractual Notice - EOT Application
14 Template Contractual Notice - EOT Application14 Template Contractual Notice - EOT Application
14 Template Contractual Notice - EOT Application
 
Harnessing WebAssembly for Real-time Stateless Streaming Pipelines
Harnessing WebAssembly for Real-time Stateless Streaming PipelinesHarnessing WebAssembly for Real-time Stateless Streaming Pipelines
Harnessing WebAssembly for Real-time Stateless Streaming Pipelines
 
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODELDEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
 
Low power architecture of logic gates using adiabatic techniques
Low power architecture of logic gates using adiabatic techniquesLow power architecture of logic gates using adiabatic techniques
Low power architecture of logic gates using adiabatic techniques
 
6th International Conference on Machine Learning & Applications (CMLA 2024)
6th International Conference on Machine Learning & Applications (CMLA 2024)6th International Conference on Machine Learning & Applications (CMLA 2024)
6th International Conference on Machine Learning & Applications (CMLA 2024)
 
bank management system in java and mysql report1.pdf
bank management system in java and mysql report1.pdfbank management system in java and mysql report1.pdf
bank management system in java and mysql report1.pdf
 
CSM Cloud Service Management Presentarion
CSM Cloud Service Management PresentarionCSM Cloud Service Management Presentarion
CSM Cloud Service Management Presentarion
 
International Conference on NLP, Artificial Intelligence, Machine Learning an...
International Conference on NLP, Artificial Intelligence, Machine Learning an...International Conference on NLP, Artificial Intelligence, Machine Learning an...
International Conference on NLP, Artificial Intelligence, Machine Learning an...
 
ML Based Model for NIDS MSc Updated Presentation.v2.pptx
ML Based Model for NIDS MSc Updated Presentation.v2.pptxML Based Model for NIDS MSc Updated Presentation.v2.pptx
ML Based Model for NIDS MSc Updated Presentation.v2.pptx
 
5214-1693458878915-Unit 6 2023 to 2024 academic year assignment (AutoRecovere...
5214-1693458878915-Unit 6 2023 to 2024 academic year assignment (AutoRecovere...5214-1693458878915-Unit 6 2023 to 2024 academic year assignment (AutoRecovere...
5214-1693458878915-Unit 6 2023 to 2024 academic year assignment (AutoRecovere...
 
digital fundamental by Thomas L.floydl.pdf
digital fundamental by Thomas L.floydl.pdfdigital fundamental by Thomas L.floydl.pdf
digital fundamental by Thomas L.floydl.pdf
 
PPT on GRP pipes manufacturing and testing
PPT on GRP pipes manufacturing and testingPPT on GRP pipes manufacturing and testing
PPT on GRP pipes manufacturing and testing
 
Recycled Concrete Aggregate in Construction Part III
Recycled Concrete Aggregate in Construction Part IIIRecycled Concrete Aggregate in Construction Part III
Recycled Concrete Aggregate in Construction Part III
 
132/33KV substation case study Presentation
132/33KV substation case study Presentation132/33KV substation case study Presentation
132/33KV substation case study Presentation
 
Properties Railway Sleepers and Test.pptx
Properties Railway Sleepers and Test.pptxProperties Railway Sleepers and Test.pptx
Properties Railway Sleepers and Test.pptx
 
2. Operations Strategy in a Global Environment.ppt
2. Operations Strategy in a Global Environment.ppt2. Operations Strategy in a Global Environment.ppt
2. Operations Strategy in a Global Environment.ppt
 
Exception Handling notes in java exception
Exception Handling notes in java exceptionException Handling notes in java exception
Exception Handling notes in java exception
 
Question paper of renewable energy sources
Question paper of renewable energy sourcesQuestion paper of renewable energy sources
Question paper of renewable energy sources
 
Heat Resistant Concrete Presentation ppt
Heat Resistant Concrete Presentation pptHeat Resistant Concrete Presentation ppt
Heat Resistant Concrete Presentation ppt
 

chap11.ppt

  • 1. Data Structures Using C++ 1 Chapter 11 Binary Trees
  • 2. Data Structures Using C++ 2 Chapter Objectives • Learn about binary trees • Explore various binary tree traversal algorithms • Learn how to organize data in a binary search tree • Discover how to insert and delete items in a binary search tree • Explore nonrecursive binary tree traversal algorithms • Learn about AVL (height-balanced) trees
  • 3. Data Structures Using C++ 3 Binary Trees • Definition: A binary tree, T, is either empty or such that: – T has a special node called the root node; – T has two sets of nodes, LT and RT, called the left subtree and right subtree of T, respectively; – LT and RT are binary trees
  • 4. Data Structures Using C++ 4 Binary Tree
  • 5. Data Structures Using C++ 5 Binary Tree With One Node The root node of the binary tree = A LA = empty RA = empty
  • 6. Data Structures Using C++ 6 Binary Trees With Two Nodes
  • 7. Data Structures Using C++ 7 Binary Trees With Two Nodes
  • 8. Data Structures Using C++ 8 Various Binary Trees With Three Nodes
  • 9. Data Structures Using C++ 9 Binary Trees Following struct defines the node of a binary tree: template<class elemType> struct nodeType { elemType info; nodeType<elemType> *llink; nodeType<elemType> *rlink; };
  • 10. Data Structures Using C++ 10 Nodes • For each node: – Data is stored in info – The pointer to the left child is stored in llink – The pointer to the right child is stored in rlink
  • 11. Data Structures Using C++ 11 General Binary Tree
  • 12. Data Structures Using C++ 12 Binary Tree Definitions • Leaf: node that has no left and right children • Parent: node with at least one child node • Level of a node: number of branches on the path from root to node • Height of a binary tree: number of nodes no the longest path from root to node
  • 13. Data Structures Using C++ 13 Height of a Binary Tree Recursive algorithm to find height of binary tree: (height(p) denotes height of binary tree with root p): if(p is NULL) height(p) = 0 else height(p) = 1 + max(height(p->llink), height(p- >rlink))
  • 14. Data Structures Using C++ 14 Height of a Binary Tree Function to implement above algorithm: template<class elemType> int height(nodeType<elemType> *p) { if(p == NULL) return 0; else return 1 + max(height(p->llink), height(p->rlink)); }
  • 15. Data Structures Using C++ 15 Copy Tree • Useful operation on binary trees is to make identical copy of binary tree • Use function copyTree when we overload assignment operator and implement copy constructor
  • 16. Data Structures Using C++ 16 Copy Tree template<class elemType> void copyTree(nodeType<elemType>* &copiedTreeRoot, nodeType<elemType>* otherTreeRoot) { if(otherTreeRoot == NULL) copiedTreeRoot = NULL; else { copiedTreeRoot = new nodeType<elemType>; copiedTreeRoot->info = otherTreeRoot->info; copyTree(copiedTreeRoot->llink, otherTreeRoot->llink); copyTree(copiedTreeRoot->rlink, otherTreeRoot->rlink); } }//end copyTree
  • 17. Data Structures Using C++ 17 Binary Tree Traversal • Must start with the root, then – Visit the node first or – Visit the subtrees first • Three different traversals – Inorder – Preorder – Postorder
  • 18. Data Structures Using C++ 18 Traversals • Inorder – Traverse the left subtree – Visit the node – Traverse the right subtree • Preorder – Visit the node – Traverse the left subtree – Traverse the right subtree
  • 19. Data Structures Using C++ 19 Traversals • Postorder – Traverse the left subtree – Traverse the right subtree – Visit the node
  • 20. Data Structures Using C++ 20 Binary Tree: Inorder Traversal
  • 21. Data Structures Using C++ 21 Binary Tree: Inorder Traversal template<class elemType> void inorder(nodeType<elemType> *p) { if(p != NULL) { inorder(p->llink); cout<<p->info<<” “; inorder(p->rlink); } }
  • 22. Data Structures Using C++ 22 Binary Tree: Traversals template<class elemType> void preorder(nodeType<elemType> *p) { if(p != NULL) { cout<<p->info<<” “; preorder(p->llink); preorder(p->rlink); } } template<class elemType> void postorder(nodeType<elemType> *p) { if(p != NULL) { postorder(p->llink); postorder(p->rlink); cout<<p->info<<” “; } }1
  • 23. Data Structures Using C++ 23 Implementing Binary Trees: class binaryTreeType Functions • Public – isEmpty – inorderTraversal – preorderTraversal – postorderTraversal – treeHeight – treeNodeCount – treeLeavesCount – destroyTree • Private • copyTree • Destroy • Inorder, preorder, postorder • Height • Max • nodeCount • leavesCount
  • 24. Data Structures Using C++ 24 Binary Search Trees • Data in each node – Larger than the data in its left child – Smaller than the data in its right child • A binary search tree,t, is either empty or: – T has a special node called the root node – T has two sets of nodes, LT and RT, called the left subtree and right subtree of T, respectively – Key in root node larger than every key in left subtree and smaller than every key in right subtree – LT and RT are binary search trees
  • 25. Data Structures Using C++ 25 Binary Search Trees
  • 26. Data Structures Using C++ 26 Operations Performed on Binary Search Trees • Determine whether the binary search tree is empty • Search the binary search tree for a particular item • Insert an item in the binary search tree • Delete an item from the binary search tree
  • 27. Data Structures Using C++ 27 Operations Performed on Binary Search Trees • Find the height of the binary search tree • Find the number of nodes in the binary search tree • Find the number of leaves in the binary search tree • Traverse the binary search tree • Copy the binary search tree
  • 28. Data Structures Using C++ 28 Binary Search Tree Analysis Worst Case: Linear tree
  • 29. Data Structures Using C++ 29 Binary Search Tree Analysis • Theorem: Let T be a binary search tree with n nodes, where n > 0.The average number of nodes visited in a search of T is approximately 1.39log2n • Number of comparisons required to determine whether x is in T is one more than the number of comparisons required to insert x in T • Number of comparisons required to insert x in T same as the number of comparisons made in unsuccessful search, reflecting that x is not in T
  • 30. Data Structures Using C++ 30 Binary Search Tree Analysis It follows that: It is also known that: Solving Equations (11-1) and (11-2)
  • 31. Data Structures Using C++ 31 Nonrecursive Inorder Traversal
  • 32. Data Structures Using C++ 32 Nonrecursive Inorder Traversal: General Algorithm 1. current = root; //start traversing the binary tree at // the root node 2. while(current is not NULL or stack is nonempty) if(current is not NULL) { push current onto stack; current = current->llink; } else { pop stack into current; visit current; //visit the node current = current->rlink; //move to the //right child }
  • 33. Data Structures Using C++ 33 Nonrecursive Preorder Traversal: General Algorithm 1. current = root; //start the traversal at the root node 2. while(current is not NULL or stack is nonempty) if(current is not NULL) { visit current; push current onto stack; current = current->llink; } else { pop stack into current; current = current->rlink; //prepare to visit //the right subtree }
  • 34. Data Structures Using C++ 34 Nonrecursive Postorder Traversal 1. current = root; //start traversal at root node 2. v = 0; 3. if(current is NULL) the binary tree is empty 4. if(current is not NULL) a. push current into stack; b. push 1 onto stack; c. current = current->llink; d. while(stack is not empty) if(current is not NULL and v is 0) { push current and 1 onto stack; current = current->llink; }
  • 35. Data Structures Using C++ 35 Nonrecursive Postorder Traversal (Continued) else { pop stack into current and v; if(v == 1) { push current and 2 onto stack; current = current->rlink; v = 0; } else visit current; }
  • 36. Data Structures Using C++ 36 AVL (Height-balanced Trees) • A perfectly balanced binary tree is a binary tree such that: – The height of the left and right subtrees of the root are equal – The left and right subtrees of the root are perfectly balanced binary trees
  • 37. Data Structures Using C++ 37 Perfectly Balanced Binary Tree
  • 38. Data Structures Using C++ 38 AVL (Height-balanced Trees) • An AVL tree (or height-balanced tree) is a binary search tree such that: – The height of the left and right subtrees of the root differ by at most 1 – The left and right subtrees of the root are AVL trees
  • 39. Data Structures Using C++ 39 AVL Trees
  • 40. Data Structures Using C++ 40 Non-AVL Trees
  • 41. Data Structures Using C++ 41 Insertion Into AVL Tree
  • 42. Data Structures Using C++ 42 Insertion Into AVL Trees
  • 43. Data Structures Using C++ 43 Insertion Into AVL Trees
  • 44. Data Structures Using C++ 44 Insertion Into AVL Trees
  • 45. Data Structures Using C++ 45 Insertion Into AVL Trees
  • 46. Data Structures Using C++ 46 AVL Tree Rotations • Reconstruction procedure: rotating tree • left rotation and right rotation • Suppose that the rotation occurs at node x • Left rotation: certain nodes from the right subtree of x move to its left subtree; the root of the right subtree of x becomes the new root of the reconstructed subtree • Right rotation at x: certain nodes from the left subtree of x move to its right subtree; the root of the left subtree of x becomes the new root of the reconstructed subtree
  • 47. Data Structures Using C++ 47 AVL Tree Rotations
  • 48. Data Structures Using C++ 48 AVL Tree Rotations
  • 49. Data Structures Using C++ 49 AVL Tree Rotations
  • 50. Data Structures Using C++ 50 AVL Tree Rotations
  • 51. Data Structures Using C++ 51 AVL Tree Rotations
  • 52. Data Structures Using C++ 52 AVL Tree Rotations
  • 53. Data Structures Using C++ 53 Deletion From AVL Trees • Case 1: the node to be deleted is a leaf • Case 2: the node to be deleted has no right child, that is, its right subtree is empty • Case 3: the node to be deleted has no left child, that is, its left subtree is empty • Case 4: the node to be deleted has a left child and a right child
  • 54. Data Structures Using C++ 54 Analysis: AVL Trees Consider all the possible AVL trees of height h. Let Th be an AVL tree of height h such that Th has the fewest number of nodes. Let Thl denote the left subtree of Th and Thr denote the right subtree of Th. Then: where | Th | denotes the number of nodes in Th.
  • 55. Data Structures Using C++ 55 Analysis: AVL Trees Suppose that Thl is of height h – 1 and Thr is of height h – 2. Thl is an AVL tree of height h – 1 such that Thl has the fewest number of nodes among all AVL trees of height h – 1. Thr is an AVL tree of height h – 2 that has the fewest number of nodes among all AVL trees of height h – 2. Thl is of the form Th -1 and Thr is of the form Th -2. Hence:
  • 56. Data Structures Using C++ 56 Analysis: AVL Trees Let Fh+2 = |Th | + 1. Then: Called a Fibonacci sequence; solution to Fh is given by: Hence From this it can be concluded that
  • 57. Data Structures Using C++ 57 Chapter Summary • Binary trees • Binary search trees • Recursive traversal algorithms • Nonrecursive traversal algorithms • AVL trees