1 Search Trees - Motivation Assume you would like to store several (key, value) pairs in a data structure that would support the following operations efficiently.

Slides:



Advertisements
Similar presentations
Chapter 12 Binary Search Trees
Advertisements

§2 Binary Trees Note: In a tree, the order of children does not matter. But in a binary tree, left child and right child are different. A B A B andare.
Comp 122, Spring 2004 Binary Search Trees. btrees - 2 Comp 122, Spring 2004 Binary Trees  Recursive definition 1.An empty tree is a binary tree 2.A node.
CS 332: Algorithms Binary Search Trees. Review: Dynamic Sets ● Next few lectures will focus on data structures rather than straight algorithms ● In particular,
ALGORITHMS THIRD YEAR BANHA UNIVERSITY FACULTY OF COMPUTERS AND INFORMATIC Lecture six Dr. Hamdy M. Mousa.
1 abstract containers hierarchical (1 to many) graph (many to many) first ith last sequence/linear (1 to 1) set.
Binary Trees, Binary Search Trees CMPS 2133 Spring 2008.
Binary Trees, Binary Search Trees COMP171 Fall 2006.
InOrder Traversal Algorithm // InOrder traversal algorithm inOrder(TreeNode n) { if (n != null) { inOrder(n.getLeft()); visit(n) inOrder(n.getRight());
Data Structures: Trees i206 Fall 2010 John Chuang Some slides adapted from Marti Hearst, Brian Hayes, or Glenn Brookshear.
Binary Trees Terminology A graph G = is a collection of nodes and edges. An edge (v 1,v 2 ) is a pair of vertices that are directly connected. A path,
CSE 326 Binary Search Trees David Kaplan Dept of Computer Science & Engineering Autumn 2001.
CSE 326: Data Structures Binary Search Trees Ben Lerner Summer 2007.
BST Data Structure A BST node contains: A BST contains
Lec 15 April 9 Topics: l binary Trees l expression trees Binary Search Trees (Chapter 5 of text)
CSE 326: Data Structures Lecture #7 Binary Search Trees Alon Halevy Spring Quarter 2001.
1 Binary Search Trees (BSTs). 2 Consider the search operation FindKey (): find an element of a particular key value in a binary tree. This operation takes.
1 abstract containers hierarchical (1 to many) graph (many to many) first ith last sequence/linear (1 to 1) set.
CSE 326: Data Structures Lecture #8 Binary Search Trees Alon Halevy Spring Quarter 2001.
David Luebke 1 7/2/2015 ITCS 6114 Binary Search Trees.
1 BST Trees A binary search tree is a binary tree in which every node satisfies the following: the key of every node in the left subtree is.
Chapter 08 Binary Trees and Binary Search Trees © John Urrutia 2013, All Rights Reserved.
More Trees COL 106 Amit Kumar and Shweta Agrawal Most slides courtesy : Douglas Wilhelm Harder, MMath, UWaterloo
CSE373: Data Structures & Algorithms Lecture 6: Binary Search Trees Nicki Dell Spring 2014 CSE373: Data Structures & Algorithms1.
CSE373: Data Structures & Algorithms Lecture 6: Binary Search Trees Lauren Milne Summer
CSCE 3110 Data Structures & Algorithm Analysis Binary Search Trees Reading: Chap. 4 (4.3) Weiss.
Chapter 19 - basic definitions - order statistics ( findkth( ) ) - balanced binary search trees - Java implementations Binary Search Trees 1CSCI 3333 Data.
Lecture Objectives  To learn how to use a tree to represent a hierarchical organization of information  To learn how to use recursion to process trees.
Dictionaries CS 105. L11: Dictionaries Slide 2 Definition The Dictionary Data Structure structure that facilitates searching objects are stored with search.
David Luebke 1 9/18/2015 CS 332: Algorithms Red-Black Trees.
1 2-D Trees You are given a set of points on the plane –Each point is defined by two coordinates (x, y) (5,45) (25,35) (35,40) (50,10) (90,5) (85,15) (80,65)
Binary Trees, Binary Search Trees RIZWAN REHMAN CENTRE FOR COMPUTER STUDIES DIBRUGARH UNIVERSITY.
1 Chapter 10 Trees. 2 Definition of Tree A tree is a set of linked nodes, such that there is one and only one path from a unique node (called the root.
Binary SearchTrees [CLRS] – Chap 12. What is a binary tree ? A binary tree is a linked data structure in which each node is an object that contains following.
Binary Search Trees (10.1) CSE 2011 Winter November 2015.
Topic 15 The Binary Search Tree ADT Binary Search Tree A binary search tree (BST) is a binary tree with an ordering property of its elements, such.
Data Structures Haim Kaplan and Uri Zwick November 2012 Lecture 3 Dynamic Sets / Dictionaries Binary Search Trees.
Lec 15 Oct 18 Binary Search Trees (Chapter 5 of text)
1 10. Binary Trees Read Sec A. Introduction: Searching a linked list. 1. Linear Search /* Linear search a list for a particular item */ 1. Set.
3.1. Binary Search Trees   . Ordered Dictionaries Keys are assumed to come from a total order. Old operations: insert, delete, find, …
David Stotts Computer Science Department UNC Chapel Hill.
CISC 235 Topic 3 General Trees, Binary Trees, Binary Search Trees.
Binary Tree. Some Terminologies Short review on binary tree Tree traversals Binary Search Tree (BST)‏ Questions.
1/14/20161 BST Operations Data Structures Ananda Gunawardena.
Red-Black Trees. Review: Binary Search Trees ● Binary Search Trees (BSTs) are an important data structure for dynamic sets ● In addition to satellite.
Week 15 – Wednesday.  What did we talk about last time?  Review up to Exam 1.
Dictionaries CS 110: Data Structures and Algorithms First Semester,
1 the BSTree class  BSTreeNode has same structure as binary tree nodes  elements stored in a BSTree are a key- value pair  must be a class (or a struct)
CSE373: Data Structures & Algorithms Lecture 6: Binary Search Trees Linda Shapiro Winter 2015.
CSE373: Data Structures & Algorithms Lecture 5: Dictionary ADTs; Binary Trees Lauren Milne Summer 2015.
CS6045: Advanced Algorithms Data Structures. Dynamic Sets Next few lectures will focus on data structures rather than straight algorithms In particular,
1 Binary Search Trees. 2 Binary Search Trees Binary Search Trees The Binary Search Tree (BST) Search, Insertion and Traversal of BST Removal of nodes.
Instructor: Lilian de Greef Quarter: Summer 2017
UNIT III TREES.
Cinda Heeren / Geoffrey Tien
COMP 103 Binary Search Trees.
Lecture 7 Algorithm Analysis
Binary Search Trees Why this is a useful data structure. Terminology
Binary Trees, Binary Search Trees
Lec 12 March 9, 11 Mid-term # 1 (March 21?)
Find in a linked list? first last 7  4  3  8 NULL
Lecture 7 Algorithm Analysis
Chapter 12: Binary Search Trees
CS6045: Advanced Algorithms
Lecture 7 Algorithm Analysis
Binary Trees, Binary Search Trees
BST Insert To insert an element, we essentially do a find( ). When we reach a NULL pointer, we create a new node there. void BST::insert(const Comp &
Binary Trees, Binary Search Trees
Tree (new ADT) Terminology: A tree is a collection of elements (nodes)
Presentation transcript:

1 Search Trees - Motivation Assume you would like to store several (key, value) pairs in a data structure that would support the following operations efficiently –Insert(key, value) –Delete(key, value) –Find(key) –Min() –Max() What are your alternatives? –Use an Array –Use a Linked List

2 Search Trees - Motivation Example: Store the following keys: 3, 9, 1, 7, head N-1 A Can we make Find/Insert/Delete all O(logN)? Operation Find (Search) Insert Delete Unsorted Array O(N) O(1) Sorted Array O(logN) O(N) Unsorted List O(N) O(1) Sorted List O(N) O(1)

3 Search Trees for Efficient Search Idea: Organize the data in a search tree structure that supports efficient search operation 1.Binary search tree (BST) 2.AVL Tree 3.Splay Tree 4.Red-Black Tree 5.B Tree and B+ Tree

4 Binary Search Trees Root 2 4 <5 >5 LST RST A Binary Search Tree (BST) is a binary tree in which the value in every node is: > all values in the node’s left subtree < all values in the node’s right subtree 2 Root >2 RST

5 BST ADT Declarations left key right x struct BSTNode { BSTNode left; int key; BSTNode right; }; BST Node /* BST ADT */ class BST { private: BSTNode root; public: BST(){root=null;} void Insert(int key); void Delete(int key); BSTNode Find(int key); BSTNode Min(); BSTNode Max(); }; 7

6 BST Operations - Find Find the node containing the key and return a pointer to this node K LST RST <K>K 1.Start at the root 2.If (key == root.key) return root; 3.If (key < root.key) Search LST 4.Otherwise Search RST root 15 root <15 >15 Search for Key=13

7 BST Operations - Find BSTNode DoFind(BSTNode root, int key){ if (root == null) return null; if (key == root.key) return root; else if (key < root.key) return DoFind(root.left, key); else /* key > root.key */ return DoFind(root.right, key); } //end-DoFind Nodes visited during a search for 13 are colored with “blue” Notice that the running time of the algorithm is O(d), where d is the depth of the tree Root Search for Key=13 BSTNode Find(int key){ return DoFind(root, key); } //end-Find

8 Iterative BST Find The same algorithm can be written iteratively by “unrolling” the recursion into a while loop Iterative version is more efficient than the recursive version BSTNode Find(int key){ BSTNode p = root; while (p != null){ if (key == p.key) return p; else if (key < p.key) p = p.left; else /* key > p.key */ p = p.right; } /* end-while */ return null; } //end-Find

9 BST Operations - Min Returns a pointer to the node that contains the minimum element in the tree –Notice that the node with the minimum element can be found by following left child pointers from the root until a NULL is encountered BSTNode Min(){ if (root == null) return null; BSTNode p = root; while (p.left != null){ p = p.left; } //end-while return p; } //end-Min Root

10 BST Operations - Max Returns a pointer to the node that contains the maximum element in the tree –Notice that the node with the maximum element can be found by following right child pointers from the root until a NULL is encountered Root BSTNode Max(){ if (root == null) return null; BSTNode p = root; while (p.right != null){ p = p.right; } //end-while return p; } //end-Max

11 BST Operations – Insert(int key) Create a new node “z” and initialize it with the key to insert E.g.: Insert 14 Then, begin at the root and trace a path down the tree as if we are searching for the node that contains the key The new node must be a child of the node where we stop the search Root z Before Insertion NULL 14 z Node “z” to be inserted z->key = 14 NULL 14 After Insertion

12 BST Operations – Insert(int key) void Insert(int key){ BSTNode pp = null; /* pp is the parent of p */ BSTNode p = root; /* Start at the root and go down */ while (p != null){ pp = p; if (key == p.key) return; /* Already exists */ else if (key < p.key) p = p.left; else /* key > p.key */ p = p.right; } /* end-while */ BSTNode z = new BSTNode(); /* New node to store the key */ z.key = key; z.left = z.right = null; if (root == null) root = z; /* Inserting into empty tree */ else if (key < pp.key) pp.left = z; else pp.right = z; } //end-Insert

13 BST Operations – Delete(int key) Delete is a bit trickier. 3 cases exist 1.Node to be deleted has no children (leaf node) –Delete 9 2.Node to be deleted has a single child –Delete 7 3.Node to be deleted has 2 children –Delete 6 Root

Deletion: Case 1 – Deleting a leaf Node Deleting 9: Simply remove the node and adjust the pointers Root Root After 9 is deleted

15 Deletion: Case 2 – A node with one child Deleting 7: “Splice out” the node By making a link between its child and its parent Root Root After 7 is deleted

16 Deletion: Case 3 – Node with 2 children Deleting 6: “Splice out” 6’s successor 7, which has no left child, and replace the contents of 6 with the contents of the successor 7 Root After 6 is deleted Root Note: Instead of z’s successor, we could have spliced out z’s predecessor

17 Sorting by inorder traversal of a BST Root 2 4 BST property allows us to print out all the keys in a BST in sorted order by an inorder traversal Inorder traversal results Correctness of this claim follows by induction in BST property

18 Proof of the Claim by Induction Base: One node 5  Sorted Induction Hypothesis: Assume that the claim is true for all tree with < n nodes. Claim Proof: Consider the following tree with n nodes 1.Recall Inorder Traversal: LST – R – RST 2.LST is sorted by the Induction hypothesis since it has < n nodes 3.RST is sorted by the Induction hypothesis since it has < n nodes 4.All values in LST < R by the BST property 5.All values in RST > R by the property 6.This completes the proof. R Root RST < n nodes LST < n nodes

19 Handling Duplicates in BSTs Root 2 4 Handling Duplicates: –Increment a counter stored in item’s node Or –Use a linked list at item’s node Root

20 Threaded BSTs root 2 4 A BST is threaded if –all right child pointers, that would normally be null, point to the inorder successor of the node –all left child pointers, that would normally be null, point to the inorder predecessor of the node NULL

21 Threaded BSTs - More root 2 4 A threaded BST makes it possible –to traverse the values in the BST via a linear traversal (iterative) that is more rapid than a recursive inorder traversal –to find the predecessor or successor of a node easily NULL

22 Laziness in Data Structures A “lazy” operation is one that puts off work as much as possible in the hope that a future operation will make the current operation unnecessary

23 Lazy Deletion Idea: Mark node as deleted; no need to reorganize tree –Skip marked nodes during Find or Insert –Reorganize tree only when number of marked nodes exceeds a percentage of real nodes (e.g. 50%) –Constant time penalty only due to marked nodes – depth increases only by a constant amount if 50% are marked undeleted nodes (N nodes max N/2 marked) –Modify Insert to make use of marked nodes whenever possible e.g. when deleted value is re-inserted Gain: –Makes deletion more efficient (Consider deleting the root) –Reinsertion of a key does not require reallocation of space Can also use lazy deletion for Linked Lists

24 Application of BSTs (1) BST is used as “Map” a.k.a. “Dictionary”, i.e., a “Look-up” table –That is, BST maintains (key, value) pairs –E.g.: Academic records systems: Given SSN, return student record (SSN, StudentRecord) –E.g.: City Information System Given zip code, return city/state (zip, city/state) –E.g.: Telephone Directories Given name, return address/phone (name, Address/Phone) Can use dictionary order for strings – lexicographical order

25 Application of BSTs (2) BST is used as “Map” a.k.a. “Dictionary”, i.e., a “Look-up” table –E.g.: Dictionary Given a word, return its meaning (word, meaning) –E.g.: Information Retrieval Systems Given a word, show where it occurs in a document (word, document/line)

26 Taxonomy of BSTs O(d) search, FindMin, FindMax, Insert, Delete BUT depth “d” depends upon the order of insertion/deletion Ex: Insert the numbers in this order. The resulting tree will degenerate to a linked list-> All operations will take O(n)! root Can we do better? Can we guarantee an upper bound on the height of the tree? 1.AVL-trees 2.Splay trees 3.Red-Black trees 4.B trees, B+ trees