SlideShare une entreprise Scribd logo
1  sur  25
Télécharger pour lire hors ligne
Lecture 5:
          Dictionaries
         Steven Skiena

Department of Computer Science
 State University of New York
 Stony Brook, NY 11794–4400

http://www.cs.sunysb.edu/∼skiena
Dictionary / Dynamic Set Operations
Perhaps the most important class of data structures maintain
a set of items, indexed by keys.
 • Search(S,k) – A query that, given a set S and a key value
   k, returns a pointer x to an element in S such that key[x]
   = k, or nil if no such element belongs to S.
 • Insert(S,x) – A modifying operation that augments the set
   S with the element x.
 • Delete(S,x) – Given a pointer x to an element in the set S,
   remove x from S. Observe we are given a pointer to an
   element x, not a key value.
• Min(S), Max(S) – Returns the element of the totally
   ordered set S which has the smallest (largest) key.
 • Next(S,x), Previous(S,x) – Given an element x whose key
   is from a totally ordered set S, returns the next largest
   (smallest) element in S, or NIL if x is the maximum
   (minimum) element.
There are a variety of implementations of these dictionary
operations, each of which yield different time bounds for
various operations.
Problem of the Day
What is the asymptotic worst-case running times for each of
the seven fundamental dictionary operations when the data
structure is implemented as
 • A singly-linked unsorted list,
 • A doubly-linked unsorted list,
 • A singly-linked sorted list, and finally
 • A doubly-linked sorted list.
Solution Blank

                      singly   singly doubly doubly
                      unsorted sorted unsorted sorted
  Search(L, k)
  Insert(L, x)
  Delete(L, x)
  Successor(L, x)
  Predecessor(L, x)
  Minimum(L)
  Maximum(L)
Solution

                      singly     double     singly   doubly
 Dictionary operation unsorted   unsorted   sorted   sorted
 Search(L, k)         O(n)       O(n)       O(n)     O(n)
 Insert(L, x)         O(1)       O(1)       O(n)     O(n)
 Delete(L, x)         O(n)∗      O(1)       O(n)∗    O(1)
 Successor(L, x)      O(n)       O(n)       O(1)     O(1)
 Predecessor(L, x)    O(n)       O(n)       O(n)∗    O(1)
 Minimum(L)           O(n)       O(n)       O(1)     O(1)
 Maximum(L)           O(n)       O(n)       O(1)∗    O(1)
Binary Search Trees
Binary search trees provide a data structure which efficiently
supports all six dictionary operations.
A binary tree is a rooted tree where each node contains at
most two children.
Each child can be identified as either a left or right child.

                             parent



                      left            right
Binary Search Trees
A binary search tree labels each node x in a binary tree such
that all nodes in the left subtree of x have keys < x and all
nodes in the right subtree of x have key’s > x.
                          2


                              3


                                  7


                              6       8


                          5




The search tree labeling enables us to find where any key is.
Implementing Binary Search Trees

typedef struct tree {
      item type item;
      struct tree *parent;
      struct tree *left;
      struct tree *right;
} tree;


The parent link is optional, since we can store the pointer on
a stack when we encounter it.
Searching in a Binary Tree: Implementation

tree *search tree(tree *l, item type x)
{
      if (l == NULL) return(NULL);

      if (l->item == x) return(l);

      if (x < l->item)
            return( search tree(l->left, x) );
      else
            return( search tree(l->right, x) );
}
Searching in a Binary Tree: How Much
The algorithm works because both the left and right subtrees
of a binary search tree are binary search trees – recursive
structure, recursive algorithm.
This takes time proportional to the height of the tree, O(h).
Maximum and Minimum
Where are the maximum and minimum elements in a binary
search tree?
Finding the Minimum

tree *find minimum(tree *t)
{
      tree *min; (* pointer to minimum *)

      if (t == NULL) return(NULL);

      min = t;
      while (min->left != NULL)
            min = min->left;
      return(min);
}


Finding the max or min takes time proportional to the height
of the tree, O(h).
Where is the Predecessor: Internal Node

                                   X




                      PREDECESSOR(X)   SUCCESSOR(X)




If X has two children, its predecessor is the maximum value
in its left subtree and its successor the minimum value in its
right subtree.
Where is the Successor: Leaf Node

                             predecessor(x)




                             X




If it does not have a left child, a node’s predecessor is its first
left ancestor.
The proof of correctness comes from looking at the in-order
traversal of the tree.
In-Order Traversal

void traverse tree(tree *l)
{
      if (l != NULL) {
            traverse tree(l->left);
            process item(l->item);
            traverse tree(l->right);
      } }


                                       H

                                  A
                                           F

                                   B               G

                                       D


                                  C            E
Tree Insertion
Do a binary search to find where it should be, then replace the
termination NIL pointer with the new item.
                            1


                                    3


                                2       7


                                    6       8


                            5




Insertion takes time proportional to the height of the tree,
O(h).
insert tree(tree **l, item type x, tree *parent)
{
      tree *p; (* temporary pointer *)

      if (*l == NULL) {
            p = malloc(sizeof(tree)); (* allocate new node *)
            p->item = x;
            p->left = p->right = NULL;
            p->parent = parent;
            *l = p; (* link into parent’s record *)
            return;
      }

      if (x < (*l)->item)
            insert tree(&((*l)->left), x, *l);
      else
            insert tree(&((*l)->right), x, *l);
}
Tree Deletion
Deletion is trickier than insertion, because the node to die
may not be a leaf, and thus effect other nodes.
There are three cases:
Case (a), where the node is a leaf, is simple - just NIL out the
parents child pointer.
Case (b), where a node has one chld, the doomed node can
just be cut out.
Case (c), relabel the node as its successor (which has at most
one child when z has two children!) and delete the successor!
Cases of Deletion

            2                             2                                  2                               2


      1                  7          1                7                 1                 7             1                7



            4                8            4                 8                4                 8             5                 8


      3                  6                           6                 3                  5            3                6

             5                             5


          initial tree           delete node with zero children (3)   delete node with 1 child (6)   delete node with 2 children (4)
Binary Search Trees as Dictionaries
All six of our dictionary operations, when implemented with
binary search trees, take O(h), where h is the height of the
tree.
The best height we could hope to get is lg n, if the tree was
perfectly balanced, since
                          lg n
                                 2i ≈ n
                          i=0
But if we get unlucky with our order of insertion or deletion,
we could get linear height!
Worst Case and Average Height

insert(a)
insert(b)
insert(c)
insert(d)


                 A


                     B


                         C


                             D
Tree Insertion Analysis
In fact, binary search trees constructed with random insertion
orders on average have Θ(lg n) height.
The worst case is linear, however.
Our analysis of Quicksort will later explain why the expected
height is Θ(lg n).
Perfectly Balanced Trees
Perfectly balanced trees require a lot of work to maintain:
                                                   9


                                       5                    13


                               3               7       11             15



                           2       4       6       8   10        12        14

                       1




If we insert the key 1, we must move every single node in the
tree to rebalance it, taking Θ(n) time.
Balanced Search Trees
Therefore, when we talk about ”balanced” trees, we mean
trees whose height is O(lg n), so all dictionary operations
(insert, delete, search, min/max, successor/predecessor) take
O(lg n) time.
Extra care must be taken on insertion and deletion to
guarantee such performance, by rearranging things when they
get too lopsided.
Red-Black trees, AVL trees, 2-3 trees, splay trees, and B-trees
are examples of balanced search trees used in practice and
discussed in most data structure texts.

Contenu connexe

Tendances

1.1 binary tree
1.1 binary tree1.1 binary tree
1.1 binary treeKrish_ver2
 
lecture 12
lecture 12lecture 12
lecture 12sajinsc
 
Algorithms notes tutorials duniya
Algorithms notes   tutorials duniyaAlgorithms notes   tutorials duniya
Algorithms notes tutorials duniyaTutorialsDuniya.com
 
Algorithm chapter 6
Algorithm chapter 6Algorithm chapter 6
Algorithm chapter 6chidabdu
 
Introduction to data structure by anil dutt
Introduction to data structure by anil duttIntroduction to data structure by anil dutt
Introduction to data structure by anil duttAnil Dutt
 
Tree and binary tree
Tree and binary treeTree and binary tree
Tree and binary treeZaid Shabbir
 
Review session2
Review session2Review session2
Review session2NEEDY12345
 
Set Operations - Union Find and Bloom Filters
Set Operations - Union Find and Bloom FiltersSet Operations - Union Find and Bloom Filters
Set Operations - Union Find and Bloom FiltersAmrinder Arora
 
Data Structure In C#
Data Structure In C#Data Structure In C#
Data Structure In C#Shahzad
 
Binary tree and Binary search tree
Binary tree and Binary search treeBinary tree and Binary search tree
Binary tree and Binary search treeMayeesha Samiha
 
Absolute and Relative Clustering
Absolute and Relative ClusteringAbsolute and Relative Clustering
Absolute and Relative ClusteringToshihiro Kamishima
 
Binary Tree in Data Structure
Binary Tree in Data StructureBinary Tree in Data Structure
Binary Tree in Data StructureMeghaj Mallick
 
NTCIR11-Math2-PattaniyilN_poster
NTCIR11-Math2-PattaniyilN_posterNTCIR11-Math2-PattaniyilN_poster
NTCIR11-Math2-PattaniyilN_posterNidhin Pattaniyil
 
17. Trees and Graphs
17. Trees and Graphs17. Trees and Graphs
17. Trees and GraphsIntro C# Book
 
Splay Trees and Self Organizing Data Structures
Splay Trees and Self Organizing Data StructuresSplay Trees and Self Organizing Data Structures
Splay Trees and Self Organizing Data StructuresAmrinder Arora
 

Tendances (20)

Splay tree
Splay treeSplay tree
Splay tree
 
1.1 binary tree
1.1 binary tree1.1 binary tree
1.1 binary tree
 
lecture 12
lecture 12lecture 12
lecture 12
 
Algorithms notes tutorials duniya
Algorithms notes   tutorials duniyaAlgorithms notes   tutorials duniya
Algorithms notes tutorials duniya
 
Algorithm chapter 6
Algorithm chapter 6Algorithm chapter 6
Algorithm chapter 6
 
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
 
binary search tree
binary search treebinary search tree
binary search tree
 
Tree and binary tree
Tree and binary treeTree and binary tree
Tree and binary tree
 
Review session2
Review session2Review session2
Review session2
 
Set Operations - Union Find and Bloom Filters
Set Operations - Union Find and Bloom FiltersSet Operations - Union Find and Bloom Filters
Set Operations - Union Find and Bloom Filters
 
210 trees
210 trees210 trees
210 trees
 
Data Structure In C#
Data Structure In C#Data Structure In C#
Data Structure In C#
 
Binary tree and Binary search tree
Binary tree and Binary search treeBinary tree and Binary search tree
Binary tree and Binary search tree
 
Absolute and Relative Clustering
Absolute and Relative ClusteringAbsolute and Relative Clustering
Absolute and Relative Clustering
 
Chapter 9 ds
Chapter 9 dsChapter 9 ds
Chapter 9 ds
 
Binary Tree in Data Structure
Binary Tree in Data StructureBinary Tree in Data Structure
Binary Tree in Data Structure
 
AVL Tree Data Structure
AVL Tree Data StructureAVL Tree Data Structure
AVL Tree Data Structure
 
NTCIR11-Math2-PattaniyilN_poster
NTCIR11-Math2-PattaniyilN_posterNTCIR11-Math2-PattaniyilN_poster
NTCIR11-Math2-PattaniyilN_poster
 
17. Trees and Graphs
17. Trees and Graphs17. Trees and Graphs
17. Trees and Graphs
 
Splay Trees and Self Organizing Data Structures
Splay Trees and Self Organizing Data StructuresSplay Trees and Self Organizing Data Structures
Splay Trees and Self Organizing Data Structures
 

En vedette

CSPro Workshop P-3
CSPro Workshop P-3CSPro Workshop P-3
CSPro Workshop P-3prabhustat
 
Data dictionary template
Data dictionary templateData dictionary template
Data dictionary templateEmeka Onyekwere
 
Systems Analyst and Design - Data Dictionary
Systems Analyst and Design -  Data DictionarySystems Analyst and Design -  Data Dictionary
Systems Analyst and Design - Data DictionaryKimberly Coquilla
 
Project report on mobile shop management
Project report on mobile shop managementProject report on mobile shop management
Project report on mobile shop managementDinesh Jogdand
 
Data flow diagrams (2)
Data flow diagrams (2)Data flow diagrams (2)
Data flow diagrams (2)Ujjwal 'Shanu'
 
Dfd examples
Dfd examplesDfd examples
Dfd examplesMohit
 
Data Flow Diagram Example
Data Flow Diagram ExampleData Flow Diagram Example
Data Flow Diagram ExampleKaviarasu D
 

En vedette (11)

CSPro Workshop P-3
CSPro Workshop P-3CSPro Workshop P-3
CSPro Workshop P-3
 
Data dictionary template
Data dictionary templateData dictionary template
Data dictionary template
 
Data Dictionary
Data DictionaryData Dictionary
Data Dictionary
 
Data dictionary
Data dictionaryData dictionary
Data dictionary
 
What is a DATA DICTIONARY?
What is a DATA DICTIONARY?What is a DATA DICTIONARY?
What is a DATA DICTIONARY?
 
Systems Analyst and Design - Data Dictionary
Systems Analyst and Design -  Data DictionarySystems Analyst and Design -  Data Dictionary
Systems Analyst and Design - Data Dictionary
 
Project report on mobile shop management
Project report on mobile shop managementProject report on mobile shop management
Project report on mobile shop management
 
Data dictionary
Data dictionaryData dictionary
Data dictionary
 
Data flow diagrams (2)
Data flow diagrams (2)Data flow diagrams (2)
Data flow diagrams (2)
 
Dfd examples
Dfd examplesDfd examples
Dfd examples
 
Data Flow Diagram Example
Data Flow Diagram ExampleData Flow Diagram Example
Data Flow Diagram Example
 

Similaire à Skiena algorithm 2007 lecture05 dictionary data structure trees

Binary Search Tree
Binary Search TreeBinary Search Tree
Binary Search TreeAdityaK92
 
Binary Search Tree
Binary Search TreeBinary Search Tree
Binary Search TreeZafar Ayub
 
15-btrees.ppt
15-btrees.ppt15-btrees.ppt
15-btrees.pptplagcheck
 
5220191CS146 Data Structures and AlgorithmsC.docx
5220191CS146 Data Structures and AlgorithmsC.docx5220191CS146 Data Structures and AlgorithmsC.docx
5220191CS146 Data Structures and AlgorithmsC.docxfredharris32
 
Trees in data structure
Trees in data structureTrees in data structure
Trees in data structureAnusruti Mitra
 
Zippers: Derivatives of Regular Types
Zippers: Derivatives of Regular TypesZippers: Derivatives of Regular Types
Zippers: Derivatives of Regular TypesJay Coskey
 
nptel 2nd presentation.pptx
nptel 2nd presentation.pptxnptel 2nd presentation.pptx
nptel 2nd presentation.pptxKeshavBandil2
 
7 chapter4 trees_binary
7 chapter4 trees_binary7 chapter4 trees_binary
7 chapter4 trees_binarySSE_AndyLi
 
Binary Search Tree and AVL
Binary Search Tree and AVLBinary Search Tree and AVL
Binary Search Tree and AVLKatang Isip
 
lecture 11
lecture 11lecture 11
lecture 11sajinsc
 
(5) collections algorithms
(5) collections algorithms(5) collections algorithms
(5) collections algorithmsNico Ludwig
 

Similaire à Skiena algorithm 2007 lecture05 dictionary data structure trees (20)

Binary trees1
Binary trees1Binary trees1
Binary trees1
 
Red Black Trees
Red Black TreesRed Black Trees
Red Black Trees
 
Binary Search Tree
Binary Search TreeBinary Search Tree
Binary Search Tree
 
Binary Search Tree
Binary Search TreeBinary Search Tree
Binary Search Tree
 
Binary search tree(bst)
Binary search tree(bst)Binary search tree(bst)
Binary search tree(bst)
 
15-btrees.ppt
15-btrees.ppt15-btrees.ppt
15-btrees.ppt
 
BST.pdf
BST.pdfBST.pdf
BST.pdf
 
5220191CS146 Data Structures and AlgorithmsC.docx
5220191CS146 Data Structures and AlgorithmsC.docx5220191CS146 Data Structures and AlgorithmsC.docx
5220191CS146 Data Structures and AlgorithmsC.docx
 
UNIT II.ppt
UNIT II.pptUNIT II.ppt
UNIT II.ppt
 
Trees in data structure
Trees in data structureTrees in data structure
Trees in data structure
 
Zippers: Derivatives of Regular Types
Zippers: Derivatives of Regular TypesZippers: Derivatives of Regular Types
Zippers: Derivatives of Regular Types
 
nptel 2nd presentation.pptx
nptel 2nd presentation.pptxnptel 2nd presentation.pptx
nptel 2nd presentation.pptx
 
Trees
TreesTrees
Trees
 
7 chapter4 trees_binary
7 chapter4 trees_binary7 chapter4 trees_binary
7 chapter4 trees_binary
 
Chap 5 Tree.ppt
Chap 5 Tree.pptChap 5 Tree.ppt
Chap 5 Tree.ppt
 
Binary Search Tree and AVL
Binary Search Tree and AVLBinary Search Tree and AVL
Binary Search Tree and AVL
 
Trees
TreesTrees
Trees
 
lecture 11
lecture 11lecture 11
lecture 11
 
(5) collections algorithms
(5) collections algorithms(5) collections algorithms
(5) collections algorithms
 
BINARY SEARCH TREE
BINARY SEARCH TREEBINARY SEARCH TREE
BINARY SEARCH TREE
 

Plus de zukun

My lyn tutorial 2009
My lyn tutorial 2009My lyn tutorial 2009
My lyn tutorial 2009zukun
 
ETHZ CV2012: Tutorial openCV
ETHZ CV2012: Tutorial openCVETHZ CV2012: Tutorial openCV
ETHZ CV2012: Tutorial openCVzukun
 
ETHZ CV2012: Information
ETHZ CV2012: InformationETHZ CV2012: Information
ETHZ CV2012: Informationzukun
 
Siwei lyu: natural image statistics
Siwei lyu: natural image statisticsSiwei lyu: natural image statistics
Siwei lyu: natural image statisticszukun
 
Lecture9 camera calibration
Lecture9 camera calibrationLecture9 camera calibration
Lecture9 camera calibrationzukun
 
Brunelli 2008: template matching techniques in computer vision
Brunelli 2008: template matching techniques in computer visionBrunelli 2008: template matching techniques in computer vision
Brunelli 2008: template matching techniques in computer visionzukun
 
Modern features-part-4-evaluation
Modern features-part-4-evaluationModern features-part-4-evaluation
Modern features-part-4-evaluationzukun
 
Modern features-part-3-software
Modern features-part-3-softwareModern features-part-3-software
Modern features-part-3-softwarezukun
 
Modern features-part-2-descriptors
Modern features-part-2-descriptorsModern features-part-2-descriptors
Modern features-part-2-descriptorszukun
 
Modern features-part-1-detectors
Modern features-part-1-detectorsModern features-part-1-detectors
Modern features-part-1-detectorszukun
 
Modern features-part-0-intro
Modern features-part-0-introModern features-part-0-intro
Modern features-part-0-introzukun
 
Lecture 02 internet video search
Lecture 02 internet video searchLecture 02 internet video search
Lecture 02 internet video searchzukun
 
Lecture 01 internet video search
Lecture 01 internet video searchLecture 01 internet video search
Lecture 01 internet video searchzukun
 
Lecture 03 internet video search
Lecture 03 internet video searchLecture 03 internet video search
Lecture 03 internet video searchzukun
 
Icml2012 tutorial representation_learning
Icml2012 tutorial representation_learningIcml2012 tutorial representation_learning
Icml2012 tutorial representation_learningzukun
 
Advances in discrete energy minimisation for computer vision
Advances in discrete energy minimisation for computer visionAdvances in discrete energy minimisation for computer vision
Advances in discrete energy minimisation for computer visionzukun
 
Gephi tutorial: quick start
Gephi tutorial: quick startGephi tutorial: quick start
Gephi tutorial: quick startzukun
 
EM algorithm and its application in probabilistic latent semantic analysis
EM algorithm and its application in probabilistic latent semantic analysisEM algorithm and its application in probabilistic latent semantic analysis
EM algorithm and its application in probabilistic latent semantic analysiszukun
 
Object recognition with pictorial structures
Object recognition with pictorial structuresObject recognition with pictorial structures
Object recognition with pictorial structureszukun
 
Iccv2011 learning spatiotemporal graphs of human activities
Iccv2011 learning spatiotemporal graphs of human activities Iccv2011 learning spatiotemporal graphs of human activities
Iccv2011 learning spatiotemporal graphs of human activities zukun
 

Plus de zukun (20)

My lyn tutorial 2009
My lyn tutorial 2009My lyn tutorial 2009
My lyn tutorial 2009
 
ETHZ CV2012: Tutorial openCV
ETHZ CV2012: Tutorial openCVETHZ CV2012: Tutorial openCV
ETHZ CV2012: Tutorial openCV
 
ETHZ CV2012: Information
ETHZ CV2012: InformationETHZ CV2012: Information
ETHZ CV2012: Information
 
Siwei lyu: natural image statistics
Siwei lyu: natural image statisticsSiwei lyu: natural image statistics
Siwei lyu: natural image statistics
 
Lecture9 camera calibration
Lecture9 camera calibrationLecture9 camera calibration
Lecture9 camera calibration
 
Brunelli 2008: template matching techniques in computer vision
Brunelli 2008: template matching techniques in computer visionBrunelli 2008: template matching techniques in computer vision
Brunelli 2008: template matching techniques in computer vision
 
Modern features-part-4-evaluation
Modern features-part-4-evaluationModern features-part-4-evaluation
Modern features-part-4-evaluation
 
Modern features-part-3-software
Modern features-part-3-softwareModern features-part-3-software
Modern features-part-3-software
 
Modern features-part-2-descriptors
Modern features-part-2-descriptorsModern features-part-2-descriptors
Modern features-part-2-descriptors
 
Modern features-part-1-detectors
Modern features-part-1-detectorsModern features-part-1-detectors
Modern features-part-1-detectors
 
Modern features-part-0-intro
Modern features-part-0-introModern features-part-0-intro
Modern features-part-0-intro
 
Lecture 02 internet video search
Lecture 02 internet video searchLecture 02 internet video search
Lecture 02 internet video search
 
Lecture 01 internet video search
Lecture 01 internet video searchLecture 01 internet video search
Lecture 01 internet video search
 
Lecture 03 internet video search
Lecture 03 internet video searchLecture 03 internet video search
Lecture 03 internet video search
 
Icml2012 tutorial representation_learning
Icml2012 tutorial representation_learningIcml2012 tutorial representation_learning
Icml2012 tutorial representation_learning
 
Advances in discrete energy minimisation for computer vision
Advances in discrete energy minimisation for computer visionAdvances in discrete energy minimisation for computer vision
Advances in discrete energy minimisation for computer vision
 
Gephi tutorial: quick start
Gephi tutorial: quick startGephi tutorial: quick start
Gephi tutorial: quick start
 
EM algorithm and its application in probabilistic latent semantic analysis
EM algorithm and its application in probabilistic latent semantic analysisEM algorithm and its application in probabilistic latent semantic analysis
EM algorithm and its application in probabilistic latent semantic analysis
 
Object recognition with pictorial structures
Object recognition with pictorial structuresObject recognition with pictorial structures
Object recognition with pictorial structures
 
Iccv2011 learning spatiotemporal graphs of human activities
Iccv2011 learning spatiotemporal graphs of human activities Iccv2011 learning spatiotemporal graphs of human activities
Iccv2011 learning spatiotemporal graphs of human activities
 

Dernier

(Best) ENJOY Call Girls in Faridabad Ex | 8377087607
(Best) ENJOY Call Girls in Faridabad Ex | 8377087607(Best) ENJOY Call Girls in Faridabad Ex | 8377087607
(Best) ENJOY Call Girls in Faridabad Ex | 8377087607dollysharma2066
 
NewBase 19 April 2024 Energy News issue - 1717 by Khaled Al Awadi.pdf
NewBase  19 April  2024  Energy News issue - 1717 by Khaled Al Awadi.pdfNewBase  19 April  2024  Energy News issue - 1717 by Khaled Al Awadi.pdf
NewBase 19 April 2024 Energy News issue - 1717 by Khaled Al Awadi.pdfKhaled Al Awadi
 
Innovation Conference 5th March 2024.pdf
Innovation Conference 5th March 2024.pdfInnovation Conference 5th March 2024.pdf
Innovation Conference 5th March 2024.pdfrichard876048
 
Market Sizes Sample Report - 2024 Edition
Market Sizes Sample Report - 2024 EditionMarket Sizes Sample Report - 2024 Edition
Market Sizes Sample Report - 2024 EditionMintel Group
 
Guide Complete Set of Residential Architectural Drawings PDF
Guide Complete Set of Residential Architectural Drawings PDFGuide Complete Set of Residential Architectural Drawings PDF
Guide Complete Set of Residential Architectural Drawings PDFChandresh Chudasama
 
TriStar Gold Corporate Presentation - April 2024
TriStar Gold Corporate Presentation - April 2024TriStar Gold Corporate Presentation - April 2024
TriStar Gold Corporate Presentation - April 2024Adnet Communications
 
Organizational Structure Running A Successful Business
Organizational Structure Running A Successful BusinessOrganizational Structure Running A Successful Business
Organizational Structure Running A Successful BusinessSeta Wicaksana
 
Ten Organizational Design Models to align structure and operations to busines...
Ten Organizational Design Models to align structure and operations to busines...Ten Organizational Design Models to align structure and operations to busines...
Ten Organizational Design Models to align structure and operations to busines...Seta Wicaksana
 
APRIL2024_UKRAINE_xml_0000000000000 .pdf
APRIL2024_UKRAINE_xml_0000000000000 .pdfAPRIL2024_UKRAINE_xml_0000000000000 .pdf
APRIL2024_UKRAINE_xml_0000000000000 .pdfRbc Rbcua
 
1911 Gold Corporate Presentation Apr 2024.pdf
1911 Gold Corporate Presentation Apr 2024.pdf1911 Gold Corporate Presentation Apr 2024.pdf
1911 Gold Corporate Presentation Apr 2024.pdfShaun Heinrichs
 
Cybersecurity Awareness Training Presentation v2024.03
Cybersecurity Awareness Training Presentation v2024.03Cybersecurity Awareness Training Presentation v2024.03
Cybersecurity Awareness Training Presentation v2024.03DallasHaselhorst
 
Call Girls Contact Number Andheri 9920874524
Call Girls Contact Number Andheri 9920874524Call Girls Contact Number Andheri 9920874524
Call Girls Contact Number Andheri 9920874524najka9823
 
FULL ENJOY Call girls in Paharganj Delhi | 8377087607
FULL ENJOY Call girls in Paharganj Delhi | 8377087607FULL ENJOY Call girls in Paharganj Delhi | 8377087607
FULL ENJOY Call girls in Paharganj Delhi | 8377087607dollysharma2066
 
Traction part 2 - EOS Model JAX Bridges.
Traction part 2 - EOS Model JAX Bridges.Traction part 2 - EOS Model JAX Bridges.
Traction part 2 - EOS Model JAX Bridges.Anamaria Contreras
 
Unlocking the Future: Explore Web 3.0 Workshop to Start Earning Today!
Unlocking the Future: Explore Web 3.0 Workshop to Start Earning Today!Unlocking the Future: Explore Web 3.0 Workshop to Start Earning Today!
Unlocking the Future: Explore Web 3.0 Workshop to Start Earning Today!Doge Mining Website
 
The-Ethical-issues-ghhhhhhhhjof-Byjus.pptx
The-Ethical-issues-ghhhhhhhhjof-Byjus.pptxThe-Ethical-issues-ghhhhhhhhjof-Byjus.pptx
The-Ethical-issues-ghhhhhhhhjof-Byjus.pptxmbikashkanyari
 
Flow Your Strategy at Flight Levels Day 2024
Flow Your Strategy at Flight Levels Day 2024Flow Your Strategy at Flight Levels Day 2024
Flow Your Strategy at Flight Levels Day 2024Kirill Klimov
 
Call US-88OO1O2216 Call Girls In Mahipalpur Female Escort Service
Call US-88OO1O2216 Call Girls In Mahipalpur Female Escort ServiceCall US-88OO1O2216 Call Girls In Mahipalpur Female Escort Service
Call US-88OO1O2216 Call Girls In Mahipalpur Female Escort Servicecallgirls2057
 

Dernier (20)

(Best) ENJOY Call Girls in Faridabad Ex | 8377087607
(Best) ENJOY Call Girls in Faridabad Ex | 8377087607(Best) ENJOY Call Girls in Faridabad Ex | 8377087607
(Best) ENJOY Call Girls in Faridabad Ex | 8377087607
 
NewBase 19 April 2024 Energy News issue - 1717 by Khaled Al Awadi.pdf
NewBase  19 April  2024  Energy News issue - 1717 by Khaled Al Awadi.pdfNewBase  19 April  2024  Energy News issue - 1717 by Khaled Al Awadi.pdf
NewBase 19 April 2024 Energy News issue - 1717 by Khaled Al Awadi.pdf
 
Innovation Conference 5th March 2024.pdf
Innovation Conference 5th March 2024.pdfInnovation Conference 5th March 2024.pdf
Innovation Conference 5th March 2024.pdf
 
Market Sizes Sample Report - 2024 Edition
Market Sizes Sample Report - 2024 EditionMarket Sizes Sample Report - 2024 Edition
Market Sizes Sample Report - 2024 Edition
 
Guide Complete Set of Residential Architectural Drawings PDF
Guide Complete Set of Residential Architectural Drawings PDFGuide Complete Set of Residential Architectural Drawings PDF
Guide Complete Set of Residential Architectural Drawings PDF
 
TriStar Gold Corporate Presentation - April 2024
TriStar Gold Corporate Presentation - April 2024TriStar Gold Corporate Presentation - April 2024
TriStar Gold Corporate Presentation - April 2024
 
Organizational Structure Running A Successful Business
Organizational Structure Running A Successful BusinessOrganizational Structure Running A Successful Business
Organizational Structure Running A Successful Business
 
Ten Organizational Design Models to align structure and operations to busines...
Ten Organizational Design Models to align structure and operations to busines...Ten Organizational Design Models to align structure and operations to busines...
Ten Organizational Design Models to align structure and operations to busines...
 
APRIL2024_UKRAINE_xml_0000000000000 .pdf
APRIL2024_UKRAINE_xml_0000000000000 .pdfAPRIL2024_UKRAINE_xml_0000000000000 .pdf
APRIL2024_UKRAINE_xml_0000000000000 .pdf
 
Japan IT Week 2024 Brochure by 47Billion (English)
Japan IT Week 2024 Brochure by 47Billion (English)Japan IT Week 2024 Brochure by 47Billion (English)
Japan IT Week 2024 Brochure by 47Billion (English)
 
1911 Gold Corporate Presentation Apr 2024.pdf
1911 Gold Corporate Presentation Apr 2024.pdf1911 Gold Corporate Presentation Apr 2024.pdf
1911 Gold Corporate Presentation Apr 2024.pdf
 
Cybersecurity Awareness Training Presentation v2024.03
Cybersecurity Awareness Training Presentation v2024.03Cybersecurity Awareness Training Presentation v2024.03
Cybersecurity Awareness Training Presentation v2024.03
 
Corporate Profile 47Billion Information Technology
Corporate Profile 47Billion Information TechnologyCorporate Profile 47Billion Information Technology
Corporate Profile 47Billion Information Technology
 
Call Girls Contact Number Andheri 9920874524
Call Girls Contact Number Andheri 9920874524Call Girls Contact Number Andheri 9920874524
Call Girls Contact Number Andheri 9920874524
 
FULL ENJOY Call girls in Paharganj Delhi | 8377087607
FULL ENJOY Call girls in Paharganj Delhi | 8377087607FULL ENJOY Call girls in Paharganj Delhi | 8377087607
FULL ENJOY Call girls in Paharganj Delhi | 8377087607
 
Traction part 2 - EOS Model JAX Bridges.
Traction part 2 - EOS Model JAX Bridges.Traction part 2 - EOS Model JAX Bridges.
Traction part 2 - EOS Model JAX Bridges.
 
Unlocking the Future: Explore Web 3.0 Workshop to Start Earning Today!
Unlocking the Future: Explore Web 3.0 Workshop to Start Earning Today!Unlocking the Future: Explore Web 3.0 Workshop to Start Earning Today!
Unlocking the Future: Explore Web 3.0 Workshop to Start Earning Today!
 
The-Ethical-issues-ghhhhhhhhjof-Byjus.pptx
The-Ethical-issues-ghhhhhhhhjof-Byjus.pptxThe-Ethical-issues-ghhhhhhhhjof-Byjus.pptx
The-Ethical-issues-ghhhhhhhhjof-Byjus.pptx
 
Flow Your Strategy at Flight Levels Day 2024
Flow Your Strategy at Flight Levels Day 2024Flow Your Strategy at Flight Levels Day 2024
Flow Your Strategy at Flight Levels Day 2024
 
Call US-88OO1O2216 Call Girls In Mahipalpur Female Escort Service
Call US-88OO1O2216 Call Girls In Mahipalpur Female Escort ServiceCall US-88OO1O2216 Call Girls In Mahipalpur Female Escort Service
Call US-88OO1O2216 Call Girls In Mahipalpur Female Escort Service
 

Skiena algorithm 2007 lecture05 dictionary data structure trees

  • 1. Lecture 5: Dictionaries Steven Skiena Department of Computer Science State University of New York Stony Brook, NY 11794–4400 http://www.cs.sunysb.edu/∼skiena
  • 2. Dictionary / Dynamic Set Operations Perhaps the most important class of data structures maintain a set of items, indexed by keys. • Search(S,k) – A query that, given a set S and a key value k, returns a pointer x to an element in S such that key[x] = k, or nil if no such element belongs to S. • Insert(S,x) – A modifying operation that augments the set S with the element x. • Delete(S,x) – Given a pointer x to an element in the set S, remove x from S. Observe we are given a pointer to an element x, not a key value.
  • 3. • Min(S), Max(S) – Returns the element of the totally ordered set S which has the smallest (largest) key. • Next(S,x), Previous(S,x) – Given an element x whose key is from a totally ordered set S, returns the next largest (smallest) element in S, or NIL if x is the maximum (minimum) element. There are a variety of implementations of these dictionary operations, each of which yield different time bounds for various operations.
  • 4. Problem of the Day What is the asymptotic worst-case running times for each of the seven fundamental dictionary operations when the data structure is implemented as • A singly-linked unsorted list, • A doubly-linked unsorted list, • A singly-linked sorted list, and finally • A doubly-linked sorted list.
  • 5. Solution Blank singly singly doubly doubly unsorted sorted unsorted sorted Search(L, k) Insert(L, x) Delete(L, x) Successor(L, x) Predecessor(L, x) Minimum(L) Maximum(L)
  • 6. Solution singly double singly doubly Dictionary operation unsorted unsorted sorted sorted Search(L, k) O(n) O(n) O(n) O(n) Insert(L, x) O(1) O(1) O(n) O(n) Delete(L, x) O(n)∗ O(1) O(n)∗ O(1) Successor(L, x) O(n) O(n) O(1) O(1) Predecessor(L, x) O(n) O(n) O(n)∗ O(1) Minimum(L) O(n) O(n) O(1) O(1) Maximum(L) O(n) O(n) O(1)∗ O(1)
  • 7. Binary Search Trees Binary search trees provide a data structure which efficiently supports all six dictionary operations. A binary tree is a rooted tree where each node contains at most two children. Each child can be identified as either a left or right child. parent left right
  • 8. Binary Search Trees A binary search tree labels each node x in a binary tree such that all nodes in the left subtree of x have keys < x and all nodes in the right subtree of x have key’s > x. 2 3 7 6 8 5 The search tree labeling enables us to find where any key is.
  • 9. Implementing Binary Search Trees typedef struct tree { item type item; struct tree *parent; struct tree *left; struct tree *right; } tree; The parent link is optional, since we can store the pointer on a stack when we encounter it.
  • 10. Searching in a Binary Tree: Implementation tree *search tree(tree *l, item type x) { if (l == NULL) return(NULL); if (l->item == x) return(l); if (x < l->item) return( search tree(l->left, x) ); else return( search tree(l->right, x) ); }
  • 11. Searching in a Binary Tree: How Much The algorithm works because both the left and right subtrees of a binary search tree are binary search trees – recursive structure, recursive algorithm. This takes time proportional to the height of the tree, O(h).
  • 12. Maximum and Minimum Where are the maximum and minimum elements in a binary search tree?
  • 13. Finding the Minimum tree *find minimum(tree *t) { tree *min; (* pointer to minimum *) if (t == NULL) return(NULL); min = t; while (min->left != NULL) min = min->left; return(min); } Finding the max or min takes time proportional to the height of the tree, O(h).
  • 14. Where is the Predecessor: Internal Node X PREDECESSOR(X) SUCCESSOR(X) If X has two children, its predecessor is the maximum value in its left subtree and its successor the minimum value in its right subtree.
  • 15. Where is the Successor: Leaf Node predecessor(x) X If it does not have a left child, a node’s predecessor is its first left ancestor. The proof of correctness comes from looking at the in-order traversal of the tree.
  • 16. In-Order Traversal void traverse tree(tree *l) { if (l != NULL) { traverse tree(l->left); process item(l->item); traverse tree(l->right); } } H A F B G D C E
  • 17. Tree Insertion Do a binary search to find where it should be, then replace the termination NIL pointer with the new item. 1 3 2 7 6 8 5 Insertion takes time proportional to the height of the tree, O(h).
  • 18. insert tree(tree **l, item type x, tree *parent) { tree *p; (* temporary pointer *) if (*l == NULL) { p = malloc(sizeof(tree)); (* allocate new node *) p->item = x; p->left = p->right = NULL; p->parent = parent; *l = p; (* link into parent’s record *) return; } if (x < (*l)->item) insert tree(&((*l)->left), x, *l); else insert tree(&((*l)->right), x, *l); }
  • 19. Tree Deletion Deletion is trickier than insertion, because the node to die may not be a leaf, and thus effect other nodes. There are three cases: Case (a), where the node is a leaf, is simple - just NIL out the parents child pointer. Case (b), where a node has one chld, the doomed node can just be cut out. Case (c), relabel the node as its successor (which has at most one child when z has two children!) and delete the successor!
  • 20. Cases of Deletion 2 2 2 2 1 7 1 7 1 7 1 7 4 8 4 8 4 8 5 8 3 6 6 3 5 3 6 5 5 initial tree delete node with zero children (3) delete node with 1 child (6) delete node with 2 children (4)
  • 21. Binary Search Trees as Dictionaries All six of our dictionary operations, when implemented with binary search trees, take O(h), where h is the height of the tree. The best height we could hope to get is lg n, if the tree was perfectly balanced, since lg n 2i ≈ n i=0 But if we get unlucky with our order of insertion or deletion, we could get linear height!
  • 22. Worst Case and Average Height insert(a) insert(b) insert(c) insert(d) A B C D
  • 23. Tree Insertion Analysis In fact, binary search trees constructed with random insertion orders on average have Θ(lg n) height. The worst case is linear, however. Our analysis of Quicksort will later explain why the expected height is Θ(lg n).
  • 24. Perfectly Balanced Trees Perfectly balanced trees require a lot of work to maintain: 9 5 13 3 7 11 15 2 4 6 8 10 12 14 1 If we insert the key 1, we must move every single node in the tree to rebalance it, taking Θ(n) time.
  • 25. Balanced Search Trees Therefore, when we talk about ”balanced” trees, we mean trees whose height is O(lg n), so all dictionary operations (insert, delete, search, min/max, successor/predecessor) take O(lg n) time. Extra care must be taken on insertion and deletion to guarantee such performance, by rearranging things when they get too lopsided. Red-Black trees, AVL trees, 2-3 trees, splay trees, and B-trees are examples of balanced search trees used in practice and discussed in most data structure texts.