SlideShare a Scribd company logo
Binary Search Trees
 Key property
 Value at node
 Smaller values in left subtree
 Larger values in right subtree
 Example
 X > Y
 X < Z
Y
X
Z
Binary Search Trees
 Examples
Binary
search trees
Not a binary
search tree
5
10
30
2 25 45
5
10
45
2 25 30
5
10
30
2
25
45
Binary Tree Implementation
Class Node {
int data; // Could be int, a class, etc
Node *left, *right; // null if empty
void insert ( int data ) { … }
void delete ( int data ) { … }
Node *find ( int data ) { … }
…
}
Iterative Search of Binary Tree
Node *Find( Node *n, int key) {
while (n != NULL) {
if (n->data == key) // Found it
return n;
if (n->data > key) // In left subtree
n = n->left;
else // In right subtree
n = n->right;
}
return null;
}
Node * n = Find( root, 5);
Recursive Search of Binary Tree
Node *Find( Node *n, int key) {
if (n == NULL) // Not found
return( n );
else if (n->data == key) // Found it
return( n );
else if (n->data > key) // In left subtree
return Find( n->left, key );
else // In right subtree
return Find( n->right, key );
}
Node * n = Find( root, 5);
Example Binary Searches
 Find ( root, 2 )
5
10
30
2 25 45
5
10
30
2
25
45
10 > 2, left
5 > 2, left
2 = 2, found
5 > 2, left
2 = 2, found
root
Example Binary Searches
 Find (root, 25 )
5
10
30
2 25 45
5
10
30
2
25
45
10 < 25, right
30 > 25, left
25 = 25, found
5 < 25, right
45 > 25, left
30 > 25, left
10 < 25, right
25 = 25, found
Types of Binary Trees
 Degenerate – only one child
 Full – always two children
 Balanced – “mostly” two children
 more formal definitions exist, above are intuitive ideas
Degenerate
binary tree
Balanced
binary tree
Full binary
tree
Binary Trees Properties
 Degenerate
 Height = O(n) for n
nodes
 Similar to linked list
 Balanced
 Height = O( log(n) )
for n nodes
 Useful for searches
Degenerate
binary tree
Balanced
binary tree
Binary Search Properties
 Time of search
 Proportional to height of tree
 Balanced binary tree
 O( log(n) ) time
 Degenerate tree
 O( n ) time
 Like searching linked list / unsorted array
Binary Search Tree Construction
 How to build & maintain binary trees?
 Insertion
 Deletion
 Maintain key property (invariant)
 Smaller values in left subtree
 Larger values in right subtree
Binary Search Tree – Insertion
 Algorithm
1. Perform search for value X
2. Search will end at node Y (if X not in tree)
3. If X < Y, insert new leaf X as new left subtree for
Y
4. If X > Y, insert new leaf X as new right subtree
for Y
 Observations
 O( log(n) ) operation for balanced tree
 Insertions may unbalance tree
Example Insertion
 Insert ( 20 )
5
10
30
2 25 45
10 < 20, right
30 > 20, left
25 > 20, left
Insert 20 on left
20
template<class E, class K>
class BSTree public: Binarytree<E>
{
public:
bool search(const K &k, E &e);
BSTree<E, K> &insert(E &e);
BSTree<E,K> &delete(K &k, E &e);
};
template<class E, class K>
BSTree<E,K> &BSTree<E,K>::insert(E &e)
{
BinaryTreeNode<E> *p=root;
BinaryTreeNode<E> *pp=0;
while (p)
{pp=p;
if (e<pdata) p=pleftchild;
else if (e>pdata) p=prightchild;
else throw badinput();
}
BinaryTreeNode<E> *r=new BinaryTreeNode<E> (e)
if (root) {
if (e<ppdata) ppleftchild=r;
else pprightchild=r;}
else root=r;
return *this;
}
Binary Search Tree – Deletion
 Algorithm
1. Perform search for value X
2. If X is a leaf, delete X
3. Else // must delete internal node
a) Replace with largest value Y on left subtree
OR smallest value Z on right subtree
b) Delete replacement value (Y or Z) from subtree
Observation
 O( log(n) ) operation for balanced tree
 Deletions may unbalance tree
Example Deletion (Leaf)
 Delete ( 25 )
5
10
30
2 25 45
10 < 25, right
30 > 25, left
25 = 25, delete
5
10
30
2 45
Example Deletion (Internal Node)
 Delete ( 10 )
5
10
30
2 25 45
5
5
30
2 25 45
2
5
30
2 25 45
Replacing 10
with largest
value in left
subtree
Replacing 5
with largest
value in left
subtree
Deleting leaf
After Deleting 10
Example Deletion (Internal Node)
 Delete ( 10 )
5
10
30
2 25 45
5
25
30
2 25 45
5
25
30
2 45
Replacing 10
with smallest
value in right
subtree
Deleting leaf Resulting tree
Indexed Binary Search Tree
 Binary search tree.
 Each node has an additional field.
 leftSize = number of nodes in its left subtree+1
Example: Indexed Binary Search
Tree 20
10
6
2 8
15
40
30
25 35
7
18
1
1 2
2
5
1
1
8
1 1
2
4
leftSize values are in red
Also called Rank!
Balanced Search Trees
 Height balanced.
 AVL (Adelson-Velsky and Landis, 1962) trees
 Weight Balanced.
 Degree Balanced.
 2-3 trees
 2-3-4 trees
 red-black trees
 B-trees
AVL Tree
 binary tree
 for every node x, define its balance factor
balance factor of x = height of left subtree of x
– height of right subtree of x
 balance factor of every node x is – 1, 0, or
1
AVL Trees
An empty binary Tree is an AVL Tree. If T is a
non-empty Binary tree with and as its
left and right subtrees, then T is an AVL tree
iff (1) and are AVL trees and (2)
where and are the heights of and
L
T R
T
L
T R
T 1

 R
L h
h
L
h R
h L
T R
T
Balance Factors
0 0
0 0
1
0
-1 0
1
0
-1
1
-1
This is an AVL tree.
AVL Search Tree
 Binary Search Tree+AVL
Indexed AVL Search Tree
 Indexed Binary Search Tree+AVL
Height Of An AVL Tree
The height of an AVL tree that has n nodes is
at most 1.44 log2 (n+2).
The height of every n node binary tree is at
least log2 (n+1).
log2 (n+1) <= height <= 1.44 log2 (n+2)
Proof Of Upper Bound On Height
 Let Nh = min # of nodes in an AVL tree
whose height is h.
 N0 = 0.
 N1 = 1.
 In the worst case the height of one of the
subtrees is h-1, and the height of the other
is h-2.
Nh, h > 1
 Both L and R are AVL trees.
 The height of one is h-1.
 The height of the other is h-2.
 The subtree whose height is h-1 has Nh-1 nodes.
 The subtree whose height is h-2 has Nh-2 nodes.
 So, Nh = Nh-1 + Nh-2 + 1.
L R
Fibonacci Numbers
 F0 = 0, F1 = 1.
 Fi = Fi-1 + Fi-2 , i > 1.
 N0 = 0, N1 = 1.
 Nh = Nh-1 + Nh-2 + 1, i > 1.
 Nh = Fh+2 – 1.
 Fi ~ i/sqrt(5).
 sqrt
AVL Search Tree
0 0
0 0
1
0
-1 0
1
0
-1
1
-1
1
0
7
8
3
1 5
3
0
4
0
2
0
2
5
3
5
4
5
6
0
Balanced Search Trees
 Kinds of balanced binary search trees
 height balanced vs. weight balanced
 “Tree rotations” used to maintain balance on insert/delete
 Non-binary search trees
 2/3 trees
 each internal node has 2 or 3 children
 all leaves at same depth (height balanced)
 B-trees
 Generalization of 2/3 trees
 Each internal node has between k/2 and k children
 Each node has an array of pointers to children
 Widely used in databases
Other (Non-Search) Trees
 Parse trees
 Convert from textual representation to tree
representation
 Textual program to tree
 Used extensively in compilers
 Tree representation of data
 E.g. HTML data can be represented as a tree
 called DOM (Document Object Model) tree
 XML
 Like HTML, but used to represent data
 Tree structured
Parse Trees
 Expressions, programs, etc can be
represented by tree structures
 E.g. Arithmetic Expression Tree
 A-(C/5 * 2) + (D*5 % 4)
+
- %
A * * 4
/ 2 D 5
C 5
Tree Traversal
 Goal: visit every node of a tree
 in-order traversal
void Node::inOrder () {
if (left != NULL) {
cout << “(“; left->inOrder(); cout << “)”;
}
cout << data << endl;
if (right != NULL) right->inOrder()
}
Output: A – C / 5 * 2 + D * 5 % 4
To disambiguate: print brackets
+
- %
A * * 4
/ 2 D 5
C 5
Tree Traversal (contd.)
 pre-order and post-order:
void Node::preOrder () {
cout << data << endl;
if (left != NULL) left->preOrder ();
if (right != NULL) right->preOrder ();
}
void Node::postOrder () {
if (left != NULL) left->preOrder ();
if (right != NULL) right->preOrder ();
cout << data << endl;
}
Output: + - A * / C 5 2 % * D 5 4
Output: A C 5 / 2 * - D 5 * 4 % +
+
- %
A * * 4
/ 2 D 5
C 5
XML
 Data Representation
 E.g.
<dependency>
<object>sample1.o</object>
<depends>sample1.cpp</depends>
<depends>sample1.h</depends>
<rule>g++ -c sample1.cpp</rule>
</dependency>
 Tree representation
dependency
object depends
sample1.o sample1.cpp
depends
sample1.h
rule
g++ -c …
Graph Data Structures
 E.g: Airline networks, road networks, electrical circuits
 Nodes and Edges
 E.g. representation: class Node
 Stores name
 stores pointers to all adjacent nodes
 i,e. edge == pointer
 To store multiple pointers: use array or linked list
Ahm’bad
Delhi
Mumbai
Calcutta
Chennai
Madurai
End of Chapter
Ad

More Related Content

Similar to CS-102 BST_27_3_14v2.pdf (20)

17 Trees.ppt DSADSADSADSADSADSADSADSADSA
17 Trees.ppt DSADSADSADSADSADSADSADSADSA17 Trees.ppt DSADSADSADSADSADSADSADSADSA
17 Trees.ppt DSADSADSADSADSADSADSADSADSA
thehamzaihsan
 
part4-trees.ppt
part4-trees.pptpart4-trees.ppt
part4-trees.ppt
Suneel61
 
Trees, Binary Search Tree, AVL Tree in Data Structures
Trees, Binary Search Tree, AVL Tree in Data Structures Trees, Binary Search Tree, AVL Tree in Data Structures
Trees, Binary Search Tree, AVL Tree in Data Structures
Gurukul Kangri Vishwavidyalaya - Faculty of Engineering and Technology
 
Search data structures
Search data structuresSearch data structures
Search data structures
Ravi Pathak
 
Binary trees1
Binary trees1Binary trees1
Binary trees1
Saurabh Mishra
 
Fundamentals of data structures
Fundamentals of data structuresFundamentals of data structures
Fundamentals of data structures
Niraj Agarwal
 
Review session2
Review session2Review session2
Review session2
NEEDY12345
 
Chap 5 Tree.ppt
Chap 5 Tree.pptChap 5 Tree.ppt
Chap 5 Tree.ppt
shashankbhadouria4
 
Purely Functional Data Structures in Scala
Purely Functional Data Structures in ScalaPurely Functional Data Structures in Scala
Purely Functional Data Structures in Scala
Vladimir Kostyukov
 
data structures module III & IV.pptx
data structures module III & IV.pptxdata structures module III & IV.pptx
data structures module III & IV.pptx
rani marri
 
Data Structures
Data StructuresData Structures
Data Structures
Nitesh Bichwani
 
mitochondria moment and super computer integration.ppt
mitochondria moment and super computer integration.pptmitochondria moment and super computer integration.ppt
mitochondria moment and super computer integration.ppt
AMMAD45
 
Lecture_10 - Revised.pptx
Lecture_10 - Revised.pptxLecture_10 - Revised.pptx
Lecture_10 - Revised.pptx
RedHeart11
 
Data Structures In Scala
Data Structures In ScalaData Structures In Scala
Data Structures In Scala
Knoldus Inc.
 
bst.ppt
bst.pptbst.ppt
bst.ppt
plagcheck
 
Data structures in scala
Data structures in scalaData structures in scala
Data structures in scala
Meetu Maltiar
 
bst-class-220902051152-cdddddddddddddddddd5e6c70f.ppt
bst-class-220902051152-cdddddddddddddddddd5e6c70f.pptbst-class-220902051152-cdddddddddddddddddd5e6c70f.ppt
bst-class-220902051152-cdddddddddddddddddd5e6c70f.ppt
shesnasuneer
 
Binary Search Tree and AVL
Binary Search Tree and AVLBinary Search Tree and AVL
Binary Search Tree and AVL
Katang Isip
 
Unit 3.ppt
Unit 3.pptUnit 3.ppt
Unit 3.ppt
JITTAYASHWANTHREDDY
 
Binary Search Tree
Binary Search TreeBinary Search Tree
Binary Search Tree
AdityaK92
 
17 Trees.ppt DSADSADSADSADSADSADSADSADSA
17 Trees.ppt DSADSADSADSADSADSADSADSADSA17 Trees.ppt DSADSADSADSADSADSADSADSADSA
17 Trees.ppt DSADSADSADSADSADSADSADSADSA
thehamzaihsan
 
part4-trees.ppt
part4-trees.pptpart4-trees.ppt
part4-trees.ppt
Suneel61
 
Search data structures
Search data structuresSearch data structures
Search data structures
Ravi Pathak
 
Fundamentals of data structures
Fundamentals of data structuresFundamentals of data structures
Fundamentals of data structures
Niraj Agarwal
 
Review session2
Review session2Review session2
Review session2
NEEDY12345
 
Purely Functional Data Structures in Scala
Purely Functional Data Structures in ScalaPurely Functional Data Structures in Scala
Purely Functional Data Structures in Scala
Vladimir Kostyukov
 
data structures module III & IV.pptx
data structures module III & IV.pptxdata structures module III & IV.pptx
data structures module III & IV.pptx
rani marri
 
mitochondria moment and super computer integration.ppt
mitochondria moment and super computer integration.pptmitochondria moment and super computer integration.ppt
mitochondria moment and super computer integration.ppt
AMMAD45
 
Lecture_10 - Revised.pptx
Lecture_10 - Revised.pptxLecture_10 - Revised.pptx
Lecture_10 - Revised.pptx
RedHeart11
 
Data Structures In Scala
Data Structures In ScalaData Structures In Scala
Data Structures In Scala
Knoldus Inc.
 
Data structures in scala
Data structures in scalaData structures in scala
Data structures in scala
Meetu Maltiar
 
bst-class-220902051152-cdddddddddddddddddd5e6c70f.ppt
bst-class-220902051152-cdddddddddddddddddd5e6c70f.pptbst-class-220902051152-cdddddddddddddddddd5e6c70f.ppt
bst-class-220902051152-cdddddddddddddddddd5e6c70f.ppt
shesnasuneer
 
Binary Search Tree and AVL
Binary Search Tree and AVLBinary Search Tree and AVL
Binary Search Tree and AVL
Katang Isip
 
Binary Search Tree
Binary Search TreeBinary Search Tree
Binary Search Tree
AdityaK92
 

More from ssuser034ce1 (20)

CSN221_Lec_27 Computer Architecture and Microprocessor
CSN221_Lec_27 Computer Architecture and MicroprocessorCSN221_Lec_27 Computer Architecture and Microprocessor
CSN221_Lec_27 Computer Architecture and Microprocessor
ssuser034ce1
 
CSN221_Lec_26 Computer Architecture and Microprocessor
CSN221_Lec_26 Computer Architecture and MicroprocessorCSN221_Lec_26 Computer Architecture and Microprocessor
CSN221_Lec_26 Computer Architecture and Microprocessor
ssuser034ce1
 
CSN221_Lec_25 Computer Architecture and Microprocessor
CSN221_Lec_25 Computer Architecture and MicroprocessorCSN221_Lec_25 Computer Architecture and Microprocessor
CSN221_Lec_25 Computer Architecture and Microprocessor
ssuser034ce1
 
CSN221_Lec_36 Computer Architecture and Microprocessor
CSN221_Lec_36 Computer Architecture and MicroprocessorCSN221_Lec_36 Computer Architecture and Microprocessor
CSN221_Lec_36 Computer Architecture and Microprocessor
ssuser034ce1
 
CSN221_Lec_35 Computer Architecture and Microprocessor
CSN221_Lec_35 Computer Architecture and MicroprocessorCSN221_Lec_35 Computer Architecture and Microprocessor
CSN221_Lec_35 Computer Architecture and Microprocessor
ssuser034ce1
 
CSN221_Lec_34 Computer Architecture and Microprocessor
CSN221_Lec_34 Computer Architecture and MicroprocessorCSN221_Lec_34 Computer Architecture and Microprocessor
CSN221_Lec_34 Computer Architecture and Microprocessor
ssuser034ce1
 
CSN221_Lec_22.pdf Computer Architecture and Microprocessor
CSN221_Lec_22.pdf Computer Architecture and MicroprocessorCSN221_Lec_22.pdf Computer Architecture and Microprocessor
CSN221_Lec_22.pdf Computer Architecture and Microprocessor
ssuser034ce1
 
CSN221_Lec_17.pdf Multi Cycle Datapath Design
CSN221_Lec_17.pdf Multi Cycle Datapath DesignCSN221_Lec_17.pdf Multi Cycle Datapath Design
CSN221_Lec_17.pdf Multi Cycle Datapath Design
ssuser034ce1
 
CSN221_Lec_16.pdf MIPS ISA and Datapath design
CSN221_Lec_16.pdf MIPS ISA and Datapath designCSN221_Lec_16.pdf MIPS ISA and Datapath design
CSN221_Lec_16.pdf MIPS ISA and Datapath design
ssuser034ce1
 
CSN221_Lec_15.pdf MIPS ISA and Datapath design
CSN221_Lec_15.pdf MIPS ISA and Datapath designCSN221_Lec_15.pdf MIPS ISA and Datapath design
CSN221_Lec_15.pdf MIPS ISA and Datapath design
ssuser034ce1
 
Computer Architecture CSN221_Lec_37_SpecialTopics.pdf
Computer Architecture CSN221_Lec_37_SpecialTopics.pdfComputer Architecture CSN221_Lec_37_SpecialTopics.pdf
Computer Architecture CSN221_Lec_37_SpecialTopics.pdf
ssuser034ce1
 
CSN221_Lec_5.pdf Computer Organization, CPU Structure and Functions
CSN221_Lec_5.pdf Computer Organization, CPU Structure and FunctionsCSN221_Lec_5.pdf Computer Organization, CPU Structure and Functions
CSN221_Lec_5.pdf Computer Organization, CPU Structure and Functions
ssuser034ce1
 
CSN221_Lec_4.pdf Computer Organization & Architecture
CSN221_Lec_4.pdf Computer Organization & ArchitectureCSN221_Lec_4.pdf Computer Organization & Architecture
CSN221_Lec_4.pdf Computer Organization & Architecture
ssuser034ce1
 
CS-102 Data Structures huffman coding.pdf
CS-102 Data Structures huffman coding.pdfCS-102 Data Structures huffman coding.pdf
CS-102 Data Structures huffman coding.pdf
ssuser034ce1
 
CS-102 Data Structures HashFunction CS102.pdf
CS-102 Data Structures HashFunction CS102.pdfCS-102 Data Structures HashFunction CS102.pdf
CS-102 Data Structures HashFunction CS102.pdf
ssuser034ce1
 
CS-102 Data Structure lectures on Graphs
CS-102 Data Structure lectures on GraphsCS-102 Data Structure lectures on Graphs
CS-102 Data Structure lectures on Graphs
ssuser034ce1
 
CS-102 DS-class04a Lectures DS Class.pdf
CS-102 DS-class04a Lectures DS Class.pdfCS-102 DS-class04a Lectures DS Class.pdf
CS-102 DS-class04a Lectures DS Class.pdf
ssuser034ce1
 
CS-102 DS-class03 Class DS Lectures .pdf
CS-102 DS-class03 Class DS Lectures .pdfCS-102 DS-class03 Class DS Lectures .pdf
CS-102 DS-class03 Class DS Lectures .pdf
ssuser034ce1
 
CS-102 DS-class_01_02 Lectures Data .pdf
CS-102 DS-class_01_02 Lectures Data .pdfCS-102 DS-class_01_02 Lectures Data .pdf
CS-102 DS-class_01_02 Lectures Data .pdf
ssuser034ce1
 
CS-102 BT_24_3_14 Binary Tree Lectures.pdf
CS-102 BT_24_3_14 Binary Tree Lectures.pdfCS-102 BT_24_3_14 Binary Tree Lectures.pdf
CS-102 BT_24_3_14 Binary Tree Lectures.pdf
ssuser034ce1
 
CSN221_Lec_27 Computer Architecture and Microprocessor
CSN221_Lec_27 Computer Architecture and MicroprocessorCSN221_Lec_27 Computer Architecture and Microprocessor
CSN221_Lec_27 Computer Architecture and Microprocessor
ssuser034ce1
 
CSN221_Lec_26 Computer Architecture and Microprocessor
CSN221_Lec_26 Computer Architecture and MicroprocessorCSN221_Lec_26 Computer Architecture and Microprocessor
CSN221_Lec_26 Computer Architecture and Microprocessor
ssuser034ce1
 
CSN221_Lec_25 Computer Architecture and Microprocessor
CSN221_Lec_25 Computer Architecture and MicroprocessorCSN221_Lec_25 Computer Architecture and Microprocessor
CSN221_Lec_25 Computer Architecture and Microprocessor
ssuser034ce1
 
CSN221_Lec_36 Computer Architecture and Microprocessor
CSN221_Lec_36 Computer Architecture and MicroprocessorCSN221_Lec_36 Computer Architecture and Microprocessor
CSN221_Lec_36 Computer Architecture and Microprocessor
ssuser034ce1
 
CSN221_Lec_35 Computer Architecture and Microprocessor
CSN221_Lec_35 Computer Architecture and MicroprocessorCSN221_Lec_35 Computer Architecture and Microprocessor
CSN221_Lec_35 Computer Architecture and Microprocessor
ssuser034ce1
 
CSN221_Lec_34 Computer Architecture and Microprocessor
CSN221_Lec_34 Computer Architecture and MicroprocessorCSN221_Lec_34 Computer Architecture and Microprocessor
CSN221_Lec_34 Computer Architecture and Microprocessor
ssuser034ce1
 
CSN221_Lec_22.pdf Computer Architecture and Microprocessor
CSN221_Lec_22.pdf Computer Architecture and MicroprocessorCSN221_Lec_22.pdf Computer Architecture and Microprocessor
CSN221_Lec_22.pdf Computer Architecture and Microprocessor
ssuser034ce1
 
CSN221_Lec_17.pdf Multi Cycle Datapath Design
CSN221_Lec_17.pdf Multi Cycle Datapath DesignCSN221_Lec_17.pdf Multi Cycle Datapath Design
CSN221_Lec_17.pdf Multi Cycle Datapath Design
ssuser034ce1
 
CSN221_Lec_16.pdf MIPS ISA and Datapath design
CSN221_Lec_16.pdf MIPS ISA and Datapath designCSN221_Lec_16.pdf MIPS ISA and Datapath design
CSN221_Lec_16.pdf MIPS ISA and Datapath design
ssuser034ce1
 
CSN221_Lec_15.pdf MIPS ISA and Datapath design
CSN221_Lec_15.pdf MIPS ISA and Datapath designCSN221_Lec_15.pdf MIPS ISA and Datapath design
CSN221_Lec_15.pdf MIPS ISA and Datapath design
ssuser034ce1
 
Computer Architecture CSN221_Lec_37_SpecialTopics.pdf
Computer Architecture CSN221_Lec_37_SpecialTopics.pdfComputer Architecture CSN221_Lec_37_SpecialTopics.pdf
Computer Architecture CSN221_Lec_37_SpecialTopics.pdf
ssuser034ce1
 
CSN221_Lec_5.pdf Computer Organization, CPU Structure and Functions
CSN221_Lec_5.pdf Computer Organization, CPU Structure and FunctionsCSN221_Lec_5.pdf Computer Organization, CPU Structure and Functions
CSN221_Lec_5.pdf Computer Organization, CPU Structure and Functions
ssuser034ce1
 
CSN221_Lec_4.pdf Computer Organization & Architecture
CSN221_Lec_4.pdf Computer Organization & ArchitectureCSN221_Lec_4.pdf Computer Organization & Architecture
CSN221_Lec_4.pdf Computer Organization & Architecture
ssuser034ce1
 
CS-102 Data Structures huffman coding.pdf
CS-102 Data Structures huffman coding.pdfCS-102 Data Structures huffman coding.pdf
CS-102 Data Structures huffman coding.pdf
ssuser034ce1
 
CS-102 Data Structures HashFunction CS102.pdf
CS-102 Data Structures HashFunction CS102.pdfCS-102 Data Structures HashFunction CS102.pdf
CS-102 Data Structures HashFunction CS102.pdf
ssuser034ce1
 
CS-102 Data Structure lectures on Graphs
CS-102 Data Structure lectures on GraphsCS-102 Data Structure lectures on Graphs
CS-102 Data Structure lectures on Graphs
ssuser034ce1
 
CS-102 DS-class04a Lectures DS Class.pdf
CS-102 DS-class04a Lectures DS Class.pdfCS-102 DS-class04a Lectures DS Class.pdf
CS-102 DS-class04a Lectures DS Class.pdf
ssuser034ce1
 
CS-102 DS-class03 Class DS Lectures .pdf
CS-102 DS-class03 Class DS Lectures .pdfCS-102 DS-class03 Class DS Lectures .pdf
CS-102 DS-class03 Class DS Lectures .pdf
ssuser034ce1
 
CS-102 DS-class_01_02 Lectures Data .pdf
CS-102 DS-class_01_02 Lectures Data .pdfCS-102 DS-class_01_02 Lectures Data .pdf
CS-102 DS-class_01_02 Lectures Data .pdf
ssuser034ce1
 
CS-102 BT_24_3_14 Binary Tree Lectures.pdf
CS-102 BT_24_3_14 Binary Tree Lectures.pdfCS-102 BT_24_3_14 Binary Tree Lectures.pdf
CS-102 BT_24_3_14 Binary Tree Lectures.pdf
ssuser034ce1
 
Ad

Recently uploaded (20)

Value Stream Mapping Worskshops for Intelligent Continuous Security
Value Stream Mapping Worskshops for Intelligent Continuous SecurityValue Stream Mapping Worskshops for Intelligent Continuous Security
Value Stream Mapping Worskshops for Intelligent Continuous Security
Marc Hornbeek
 
Process Parameter Optimization for Minimizing Springback in Cold Drawing Proc...
Process Parameter Optimization for Minimizing Springback in Cold Drawing Proc...Process Parameter Optimization for Minimizing Springback in Cold Drawing Proc...
Process Parameter Optimization for Minimizing Springback in Cold Drawing Proc...
Journal of Soft Computing in Civil Engineering
 
The Gaussian Process Modeling Module in UQLab
The Gaussian Process Modeling Module in UQLabThe Gaussian Process Modeling Module in UQLab
The Gaussian Process Modeling Module in UQLab
Journal of Soft Computing in Civil Engineering
 
Machine learning project on employee attrition detection using (2).pptx
Machine learning project on employee attrition detection using (2).pptxMachine learning project on employee attrition detection using (2).pptx
Machine learning project on employee attrition detection using (2).pptx
rajeswari89780
 
Avnet Silica's PCIM 2025 Highlights Flyer
Avnet Silica's PCIM 2025 Highlights FlyerAvnet Silica's PCIM 2025 Highlights Flyer
Avnet Silica's PCIM 2025 Highlights Flyer
WillDavies22
 
theory-slides-for react for beginners.pptx
theory-slides-for react for beginners.pptxtheory-slides-for react for beginners.pptx
theory-slides-for react for beginners.pptx
sanchezvanessa7896
 
five-year-soluhhhhhhhhhhhhhhhhhtions.pdf
five-year-soluhhhhhhhhhhhhhhhhhtions.pdffive-year-soluhhhhhhhhhhhhhhhhhtions.pdf
five-year-soluhhhhhhhhhhhhhhhhhtions.pdf
AdityaSharma944496
 
Mathematical foundation machine learning.pdf
Mathematical foundation machine learning.pdfMathematical foundation machine learning.pdf
Mathematical foundation machine learning.pdf
TalhaShahid49
 
Data Structures_Searching and Sorting.pptx
Data Structures_Searching and Sorting.pptxData Structures_Searching and Sorting.pptx
Data Structures_Searching and Sorting.pptx
RushaliDeshmukh2
 
new ppt artificial intelligence historyyy
new ppt artificial intelligence historyyynew ppt artificial intelligence historyyy
new ppt artificial intelligence historyyy
PianoPianist
 
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptxLidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
RishavKumar530754
 
Smart_Storage_Systems_Production_Engineering.pptx
Smart_Storage_Systems_Production_Engineering.pptxSmart_Storage_Systems_Production_Engineering.pptx
Smart_Storage_Systems_Production_Engineering.pptx
rushikeshnavghare94
 
DT REPORT by Tech titan GROUP to introduce the subject design Thinking
DT REPORT by Tech titan GROUP to introduce the subject design ThinkingDT REPORT by Tech titan GROUP to introduce the subject design Thinking
DT REPORT by Tech titan GROUP to introduce the subject design Thinking
DhruvChotaliya2
 
some basics electrical and electronics knowledge
some basics electrical and electronics knowledgesome basics electrical and electronics knowledge
some basics electrical and electronics knowledge
nguyentrungdo88
 
introduction to machine learining for beginers
introduction to machine learining for beginersintroduction to machine learining for beginers
introduction to machine learining for beginers
JoydebSheet
 
Fort night presentation new0903 pdf.pdf.
Fort night presentation new0903 pdf.pdf.Fort night presentation new0903 pdf.pdf.
Fort night presentation new0903 pdf.pdf.
anuragmk56
 
Introduction to Zoomlion Earthmoving.pptx
Introduction to Zoomlion Earthmoving.pptxIntroduction to Zoomlion Earthmoving.pptx
Introduction to Zoomlion Earthmoving.pptx
AS1920
 
International Journal of Distributed and Parallel systems (IJDPS)
International Journal of Distributed and Parallel systems (IJDPS)International Journal of Distributed and Parallel systems (IJDPS)
International Journal of Distributed and Parallel systems (IJDPS)
samueljackson3773
 
15th International Conference on Computer Science, Engineering and Applicatio...
15th International Conference on Computer Science, Engineering and Applicatio...15th International Conference on Computer Science, Engineering and Applicatio...
15th International Conference on Computer Science, Engineering and Applicatio...
IJCSES Journal
 
Development of MLR, ANN and ANFIS Models for Estimation of PCUs at Different ...
Development of MLR, ANN and ANFIS Models for Estimation of PCUs at Different ...Development of MLR, ANN and ANFIS Models for Estimation of PCUs at Different ...
Development of MLR, ANN and ANFIS Models for Estimation of PCUs at Different ...
Journal of Soft Computing in Civil Engineering
 
Value Stream Mapping Worskshops for Intelligent Continuous Security
Value Stream Mapping Worskshops for Intelligent Continuous SecurityValue Stream Mapping Worskshops for Intelligent Continuous Security
Value Stream Mapping Worskshops for Intelligent Continuous Security
Marc Hornbeek
 
Machine learning project on employee attrition detection using (2).pptx
Machine learning project on employee attrition detection using (2).pptxMachine learning project on employee attrition detection using (2).pptx
Machine learning project on employee attrition detection using (2).pptx
rajeswari89780
 
Avnet Silica's PCIM 2025 Highlights Flyer
Avnet Silica's PCIM 2025 Highlights FlyerAvnet Silica's PCIM 2025 Highlights Flyer
Avnet Silica's PCIM 2025 Highlights Flyer
WillDavies22
 
theory-slides-for react for beginners.pptx
theory-slides-for react for beginners.pptxtheory-slides-for react for beginners.pptx
theory-slides-for react for beginners.pptx
sanchezvanessa7896
 
five-year-soluhhhhhhhhhhhhhhhhhtions.pdf
five-year-soluhhhhhhhhhhhhhhhhhtions.pdffive-year-soluhhhhhhhhhhhhhhhhhtions.pdf
five-year-soluhhhhhhhhhhhhhhhhhtions.pdf
AdityaSharma944496
 
Mathematical foundation machine learning.pdf
Mathematical foundation machine learning.pdfMathematical foundation machine learning.pdf
Mathematical foundation machine learning.pdf
TalhaShahid49
 
Data Structures_Searching and Sorting.pptx
Data Structures_Searching and Sorting.pptxData Structures_Searching and Sorting.pptx
Data Structures_Searching and Sorting.pptx
RushaliDeshmukh2
 
new ppt artificial intelligence historyyy
new ppt artificial intelligence historyyynew ppt artificial intelligence historyyy
new ppt artificial intelligence historyyy
PianoPianist
 
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptxLidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
RishavKumar530754
 
Smart_Storage_Systems_Production_Engineering.pptx
Smart_Storage_Systems_Production_Engineering.pptxSmart_Storage_Systems_Production_Engineering.pptx
Smart_Storage_Systems_Production_Engineering.pptx
rushikeshnavghare94
 
DT REPORT by Tech titan GROUP to introduce the subject design Thinking
DT REPORT by Tech titan GROUP to introduce the subject design ThinkingDT REPORT by Tech titan GROUP to introduce the subject design Thinking
DT REPORT by Tech titan GROUP to introduce the subject design Thinking
DhruvChotaliya2
 
some basics electrical and electronics knowledge
some basics electrical and electronics knowledgesome basics electrical and electronics knowledge
some basics electrical and electronics knowledge
nguyentrungdo88
 
introduction to machine learining for beginers
introduction to machine learining for beginersintroduction to machine learining for beginers
introduction to machine learining for beginers
JoydebSheet
 
Fort night presentation new0903 pdf.pdf.
Fort night presentation new0903 pdf.pdf.Fort night presentation new0903 pdf.pdf.
Fort night presentation new0903 pdf.pdf.
anuragmk56
 
Introduction to Zoomlion Earthmoving.pptx
Introduction to Zoomlion Earthmoving.pptxIntroduction to Zoomlion Earthmoving.pptx
Introduction to Zoomlion Earthmoving.pptx
AS1920
 
International Journal of Distributed and Parallel systems (IJDPS)
International Journal of Distributed and Parallel systems (IJDPS)International Journal of Distributed and Parallel systems (IJDPS)
International Journal of Distributed and Parallel systems (IJDPS)
samueljackson3773
 
15th International Conference on Computer Science, Engineering and Applicatio...
15th International Conference on Computer Science, Engineering and Applicatio...15th International Conference on Computer Science, Engineering and Applicatio...
15th International Conference on Computer Science, Engineering and Applicatio...
IJCSES Journal
 
Ad

CS-102 BST_27_3_14v2.pdf

  • 1. Binary Search Trees  Key property  Value at node  Smaller values in left subtree  Larger values in right subtree  Example  X > Y  X < Z Y X Z
  • 2. Binary Search Trees  Examples Binary search trees Not a binary search tree 5 10 30 2 25 45 5 10 45 2 25 30 5 10 30 2 25 45
  • 3. Binary Tree Implementation Class Node { int data; // Could be int, a class, etc Node *left, *right; // null if empty void insert ( int data ) { … } void delete ( int data ) { … } Node *find ( int data ) { … } … }
  • 4. Iterative Search of Binary Tree Node *Find( Node *n, int key) { while (n != NULL) { if (n->data == key) // Found it return n; if (n->data > key) // In left subtree n = n->left; else // In right subtree n = n->right; } return null; } Node * n = Find( root, 5);
  • 5. Recursive Search of Binary Tree Node *Find( Node *n, int key) { if (n == NULL) // Not found return( n ); else if (n->data == key) // Found it return( n ); else if (n->data > key) // In left subtree return Find( n->left, key ); else // In right subtree return Find( n->right, key ); } Node * n = Find( root, 5);
  • 6. Example Binary Searches  Find ( root, 2 ) 5 10 30 2 25 45 5 10 30 2 25 45 10 > 2, left 5 > 2, left 2 = 2, found 5 > 2, left 2 = 2, found root
  • 7. Example Binary Searches  Find (root, 25 ) 5 10 30 2 25 45 5 10 30 2 25 45 10 < 25, right 30 > 25, left 25 = 25, found 5 < 25, right 45 > 25, left 30 > 25, left 10 < 25, right 25 = 25, found
  • 8. Types of Binary Trees  Degenerate – only one child  Full – always two children  Balanced – “mostly” two children  more formal definitions exist, above are intuitive ideas Degenerate binary tree Balanced binary tree Full binary tree
  • 9. Binary Trees Properties  Degenerate  Height = O(n) for n nodes  Similar to linked list  Balanced  Height = O( log(n) ) for n nodes  Useful for searches Degenerate binary tree Balanced binary tree
  • 10. Binary Search Properties  Time of search  Proportional to height of tree  Balanced binary tree  O( log(n) ) time  Degenerate tree  O( n ) time  Like searching linked list / unsorted array
  • 11. Binary Search Tree Construction  How to build & maintain binary trees?  Insertion  Deletion  Maintain key property (invariant)  Smaller values in left subtree  Larger values in right subtree
  • 12. Binary Search Tree – Insertion  Algorithm 1. Perform search for value X 2. Search will end at node Y (if X not in tree) 3. If X < Y, insert new leaf X as new left subtree for Y 4. If X > Y, insert new leaf X as new right subtree for Y  Observations  O( log(n) ) operation for balanced tree  Insertions may unbalance tree
  • 13. Example Insertion  Insert ( 20 ) 5 10 30 2 25 45 10 < 20, right 30 > 20, left 25 > 20, left Insert 20 on left 20
  • 14. template<class E, class K> class BSTree public: Binarytree<E> { public: bool search(const K &k, E &e); BSTree<E, K> &insert(E &e); BSTree<E,K> &delete(K &k, E &e); }; template<class E, class K> BSTree<E,K> &BSTree<E,K>::insert(E &e) { BinaryTreeNode<E> *p=root; BinaryTreeNode<E> *pp=0; while (p) {pp=p; if (e<pdata) p=pleftchild; else if (e>pdata) p=prightchild; else throw badinput(); } BinaryTreeNode<E> *r=new BinaryTreeNode<E> (e) if (root) { if (e<ppdata) ppleftchild=r; else pprightchild=r;} else root=r; return *this; }
  • 15. Binary Search Tree – Deletion  Algorithm 1. Perform search for value X 2. If X is a leaf, delete X 3. Else // must delete internal node a) Replace with largest value Y on left subtree OR smallest value Z on right subtree b) Delete replacement value (Y or Z) from subtree Observation  O( log(n) ) operation for balanced tree  Deletions may unbalance tree
  • 16. Example Deletion (Leaf)  Delete ( 25 ) 5 10 30 2 25 45 10 < 25, right 30 > 25, left 25 = 25, delete 5 10 30 2 45
  • 17. Example Deletion (Internal Node)  Delete ( 10 ) 5 10 30 2 25 45 5 5 30 2 25 45 2 5 30 2 25 45 Replacing 10 with largest value in left subtree Replacing 5 with largest value in left subtree Deleting leaf
  • 19. Example Deletion (Internal Node)  Delete ( 10 ) 5 10 30 2 25 45 5 25 30 2 25 45 5 25 30 2 45 Replacing 10 with smallest value in right subtree Deleting leaf Resulting tree
  • 20. Indexed Binary Search Tree  Binary search tree.  Each node has an additional field.  leftSize = number of nodes in its left subtree+1
  • 21. Example: Indexed Binary Search Tree 20 10 6 2 8 15 40 30 25 35 7 18 1 1 2 2 5 1 1 8 1 1 2 4 leftSize values are in red Also called Rank!
  • 22. Balanced Search Trees  Height balanced.  AVL (Adelson-Velsky and Landis, 1962) trees  Weight Balanced.  Degree Balanced.  2-3 trees  2-3-4 trees  red-black trees  B-trees
  • 23. AVL Tree  binary tree  for every node x, define its balance factor balance factor of x = height of left subtree of x – height of right subtree of x  balance factor of every node x is – 1, 0, or 1
  • 24. AVL Trees An empty binary Tree is an AVL Tree. If T is a non-empty Binary tree with and as its left and right subtrees, then T is an AVL tree iff (1) and are AVL trees and (2) where and are the heights of and L T R T L T R T 1   R L h h L h R h L T R T
  • 25. Balance Factors 0 0 0 0 1 0 -1 0 1 0 -1 1 -1 This is an AVL tree.
  • 26. AVL Search Tree  Binary Search Tree+AVL
  • 27. Indexed AVL Search Tree  Indexed Binary Search Tree+AVL
  • 28. Height Of An AVL Tree The height of an AVL tree that has n nodes is at most 1.44 log2 (n+2). The height of every n node binary tree is at least log2 (n+1). log2 (n+1) <= height <= 1.44 log2 (n+2)
  • 29. Proof Of Upper Bound On Height  Let Nh = min # of nodes in an AVL tree whose height is h.  N0 = 0.  N1 = 1.  In the worst case the height of one of the subtrees is h-1, and the height of the other is h-2.
  • 30. Nh, h > 1  Both L and R are AVL trees.  The height of one is h-1.  The height of the other is h-2.  The subtree whose height is h-1 has Nh-1 nodes.  The subtree whose height is h-2 has Nh-2 nodes.  So, Nh = Nh-1 + Nh-2 + 1. L R
  • 31. Fibonacci Numbers  F0 = 0, F1 = 1.  Fi = Fi-1 + Fi-2 , i > 1.  N0 = 0, N1 = 1.  Nh = Nh-1 + Nh-2 + 1, i > 1.  Nh = Fh+2 – 1.  Fi ~ i/sqrt(5).  sqrt
  • 32. AVL Search Tree 0 0 0 0 1 0 -1 0 1 0 -1 1 -1 1 0 7 8 3 1 5 3 0 4 0 2 0 2 5 3 5 4 5 6 0
  • 33. Balanced Search Trees  Kinds of balanced binary search trees  height balanced vs. weight balanced  “Tree rotations” used to maintain balance on insert/delete  Non-binary search trees  2/3 trees  each internal node has 2 or 3 children  all leaves at same depth (height balanced)  B-trees  Generalization of 2/3 trees  Each internal node has between k/2 and k children  Each node has an array of pointers to children  Widely used in databases
  • 34. Other (Non-Search) Trees  Parse trees  Convert from textual representation to tree representation  Textual program to tree  Used extensively in compilers  Tree representation of data  E.g. HTML data can be represented as a tree  called DOM (Document Object Model) tree  XML  Like HTML, but used to represent data  Tree structured
  • 35. Parse Trees  Expressions, programs, etc can be represented by tree structures  E.g. Arithmetic Expression Tree  A-(C/5 * 2) + (D*5 % 4) + - % A * * 4 / 2 D 5 C 5
  • 36. Tree Traversal  Goal: visit every node of a tree  in-order traversal void Node::inOrder () { if (left != NULL) { cout << “(“; left->inOrder(); cout << “)”; } cout << data << endl; if (right != NULL) right->inOrder() } Output: A – C / 5 * 2 + D * 5 % 4 To disambiguate: print brackets + - % A * * 4 / 2 D 5 C 5
  • 37. Tree Traversal (contd.)  pre-order and post-order: void Node::preOrder () { cout << data << endl; if (left != NULL) left->preOrder (); if (right != NULL) right->preOrder (); } void Node::postOrder () { if (left != NULL) left->preOrder (); if (right != NULL) right->preOrder (); cout << data << endl; } Output: + - A * / C 5 2 % * D 5 4 Output: A C 5 / 2 * - D 5 * 4 % + + - % A * * 4 / 2 D 5 C 5
  • 38. XML  Data Representation  E.g. <dependency> <object>sample1.o</object> <depends>sample1.cpp</depends> <depends>sample1.h</depends> <rule>g++ -c sample1.cpp</rule> </dependency>  Tree representation dependency object depends sample1.o sample1.cpp depends sample1.h rule g++ -c …
  • 39. Graph Data Structures  E.g: Airline networks, road networks, electrical circuits  Nodes and Edges  E.g. representation: class Node  Stores name  stores pointers to all adjacent nodes  i,e. edge == pointer  To store multiple pointers: use array or linked list Ahm’bad Delhi Mumbai Calcutta Chennai Madurai