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.

Slides:



Advertisements
Similar presentations
S. Sudarshan Based partly on material from Fawzi Emad & Chau-Wen Tseng
Advertisements

1 abstract containers hierarchical (1 to many) graph (many to many) first ith last sequence/linear (1 to 1) set.
InOrder Traversal Algorithm // InOrder traversal algorithm inOrder(TreeNode n) { if (n != null) { inOrder(n.getLeft()); visit(n) inOrder(n.getRight());
© 2006 Pearson Addison-Wesley. All rights reserved11 B-1 Chapter 11 (continued) Trees.
Trees, Binary Trees, and Binary Search Trees COMP171.
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,
Main Index Contents 11 Main Index Contents Tree StructuresTree Structures (3 slides) Tree Structures Tree Node Level and Path Len. Tree Node Level and.
BST Data Structure A BST node contains: A BST contains
Data Structures Data Structures Topic #8. Today’s Agenda Continue Discussing Table Abstractions But, this time, let’s talk about them in terms of new.
CS 240: Data Structures Thursday, August 2nd Trees – Traversals, Representations, Recursion and Helpers.
1 abstract containers hierarchical (1 to many) graph (many to many) first ith last sequence/linear (1 to 1) set.
Marc Smith and Jim Ten Eyck
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.
More Trees COL 106 Amit Kumar and Shweta Agrawal Most slides courtesy : Douglas Wilhelm Harder, MMath, UWaterloo
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.
Recursion Bryce Boe 2013/11/18 CS24, Fall Outline Wednesday Recap Lab 7 Iterative Solution Recursion Binary Tree Traversals Lab 7 Recursive Solution.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Templatized Tree.
Searching: Binary Trees and Hash Tables CHAPTER 12 6/4/15 Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education,
© 2011 Pearson Addison-Wesley. All rights reserved 11 B-1 Chapter 11 (continued) Trees.
Binary Trees Chapter 10. Introduction Previous chapter considered linked lists –nodes connected by two or more links We seek to organize data in a linked.
CISC220 Fall 2009 James Atlas Lecture 13: Trees. Skip Lists.
1 Trees A tree is a data structure used to represent different kinds of data and help solve a number of algorithmic problems Game trees (i.e., chess ),
INTRODUCTION TO BINARY TREES P SORTING  Review of Linear Search: –again, begin with first element and search through list until finding element,
DATA STRUCTURES AND ALGORITHMS Lecture Notes 5 Prepared by İnanç TAHRALI.
A Binary Search Tree Binary Search Trees.
Prof. Amr Goneid, AUC1 Analysis & Design of Algorithms (CSCE 321) Prof. Amr Goneid Department of Computer Science, AUC Part R2. Binary Search Trees.
Pointers & Dynamic Data Structures Chapter Dynamic Data Structures t Arrays & structs are static (compile time) t Dynamic expand as program executes.
Trees, Binary Trees, and Binary Search Trees COMP171.
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.
 Trees Data Structures Trees Data Structures  Trees Trees  Binary Search Trees Binary Search Trees  Binary Tree Implementation Binary Tree Implementation.
Prof. Amr Goneid, AUC1 CSCI 210 Data Structures and Algorithms Prof. Amr Goneid AUC Part 5. Dictionaries(2): Hash Tables.
CS 206 Introduction to Computer Science II 02 / 13 / 2009 Instructor: Michael Eckmann.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 16. Linked Lists.
Search: Binary Search Trees Dr. Yingwu Zhu. Linear Search Collection of data items to be searched is organized in a list x 1, x 2, … x n Assume == and.
Binary Trees Chapter 10. Introduction Previous chapter considered linked lists –nodes connected by two or more links We seek to organize data in a linked.
CMSC 341 Introduction to Trees. 2/21/20062 Tree ADT Tree definition –A tree is a set of nodes which may be empty –If not empty, then there is a distinguished.
1 Binary Trees and Binary Search Trees Based on Dale & Co: Object-Oriented Data Structures using C++ (graphics)
CSCS-200 Data Structure and Algorithms Lecture
Binary Search Tree. Tree  A nonlinear data structure consisting of nodes, each of which contains data and pointers to other nodes.  Each node has only.
ADT Binary Search Tree Ellen Walker CPSC 201 Data Structures Hiram College.
Prof. Amr Goneid, AUC1 CSCE 210 Data Structures and Algorithms Prof. Amr Goneid AUC Part 6. Dictionaries(3): Binary Search Trees.
Binary Search Trees (BST)
Prof. Amr Goneid, AUC1 Analysis & Design of Algorithms (CSCE 321) Prof. Amr Goneid Department of Computer Science, AUC Part R3. Priority Queues.
Copyright © 2012 Pearson Education, Inc. Chapter 20: Binary Trees.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 15. Dictionaries (1): A Key Table Class.
CMSC 202, Version 5/02 1 Trees. CMSC 202, Version 5/02 2 Tree Basics 1.A tree is a set of nodes. 2.A tree may be empty (i.e., contain no nodes). 3.If.
Search: Binary Search Trees Dr. Yingwu Zhu. Review: Linear Search Collection of data items to be searched is organized in a list x 1, x 2, … x n – Assume.
CS 240Chapter 10 – TreesPage Chapter 10 Trees The tree abstract data type provides a hierarchical to the representation of certain types of relationships.
1 Trees. 2 Trees Trees. Binary Trees Tree Traversal.
CSCE 210 Data Structures and Algorithms
CSCE 210 Data Structures and Algorithms
CS505 Data Structures and Algorithms
CSCE 210 Data Structures and Algorithms
Trees Chapter 11 (continued)
Binary Trees and Binary Search Trees
Trees Chapter 11 (continued)
BST Trees
UNIT III TREES.
Binary Search Tree (BST)
CMSC 341 Introduction to Trees.
abstract containers sequence/linear (1 to 1) hierarchical (1 to many)
Chapter 20: Binary Trees.
Map interface Empty() - return true if the map is empty; else return false Size() - return the number of elements in the map Find(key) - if there is an.
Chapter 21: Binary Trees.
Searching: Binary Trees
Chapter 16 Tree Implementations
Chapter 10 1 – Binary Trees Tree Structures (3 slides)
Pointers & Dynamic Data Structures
Data Structures Using C++ 2E
Chapter 11 Trees © 2011 Pearson Addison-Wesley. All rights reserved.
Presentation transcript:

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 from a BST Binary Search Tree ADT Template Class Specification Other Search Trees (AVL Trees)

3 The Binary Search Tree (BST) A BST is a binary tree that stores keys or key-data pairs in its nodes and has the following properties: A key identifies uniquely the node (no duplicate keys) If (u, v, w) are nodes such that (u) is any node in the left subtree of (v) and (w) is any node in the right subtree of (v) then: key(u) < key(v) < key(w) vuw

4 Examples Of BST

5 These are NOT BSTs.

6 3. Search, Insertion & Traversal of BST Search (tree, target) if (tree is empty) target is not in the tree; else if (the target key is the root) target found in root; else if (target key smaller than the root’s key) search left sub-tree; elsesearch right sub-tree;

7 Searching Algorithm (Pseudo Code) Searches for the item with same key as k in the tree (t). Bool search(t,k) { if (t is empty)return false; else if (k == key(t))return true; else if (k < key(t)) return search(t left, k); else return search(t right, k); }

8 Searching for a key Search for the node containing e:

9 Building a Binary Search Tree Tree created from root downward Item 1 stored in root Next item is attached to left tree if value is smaller or right tree if value is larger To insert an item into an existing tree, we must first locate the item’s parent and then insert

10 Algorithm for Insertion Insert (tree, new_item) if (tree is empty) insert new item as root; else if (root key matches item) skip insertion; (duplicate key) else if (new key is smaller than root) insert in left sub-tree; elseinsert in right sub-tree;

11 Insertion (Pseudo Code) Inserts key (k)in the tree (t) Bool insert(t, k) { if (t is empty) { create node containing (k)and attach to (t); return true; } else if (k == key(t)) return false; else if (k < key(t)) return insert(t left, k); else return insert(t right, k); }

12 Example: Building a Tree Insert: 40,20,10,50,65,45,30

13 Linked Representation The nodes in the BST will be implemented as a linked structure: left element right t

Prof. Amr Goneid, AUC14 Traversing a Binary Search Tree Recursive inorder traversal of tree with root (t) traverse ( t ) { if (t is not empty) traverse ( t left ); visit (t); traverse ( t right ); }

15 Find Minimum Key Find the minimum key in a tree with root (t) Minkey ( t ) { if ( t left is not empty) return MinKey( t left ); else return key(t); }

16 Other Traversal Orders Pre-order (a.k.a. Depth-First traversal) can be implemented using an iterative (non-recursive) algorithm. In this case, a stack is used If the stack is replaced by a queue and left pointers are exchanged by right pointers, the algorithm becomes Level- order traversal (a.k.a. Breadth-First traversal)

17 Iterative Preorder Traversal void iterative_preorder ( ) { t = root; Let s be a stack s.push (t); while(!s.stackIsEmpty()) {s.pop(t); process(t->key); if ( t right is not empty) s.push(t right ); if ( t left is not empty) s.push(t left ); }

18 Pre-Order Traversal Traversal order: {D,B,A,C,F,E,G} D BF ACEG

19 Level Order Traversal void levelorder ( ) { t = root; Let q be a queue; q.enqueue(t); while(!q.queueIsEmpty()) {q.dequeue(t); process(t->key); if ( t left is not empty) q.enqueue(t left ); if ( t right is not empty) q.enqueue(t right ); }

20 Level-Order Traversal Traversal order: {D,B,F,A,C,E,G} ACEG BF D

21 4. Removal of Nodes from a BST

22 Deleting a ROOT Node

23 Deleting a ROOT Node

24 Deleting a ROOT Node (Special Case)

25 Deleting a ROOT Node (Alternative)

26 Deleting an Internal Node

27 Search for Parent of a Node To delete a node, we need to find its parent. To search for the parent (p) of a node (x) with key (k) in tree (t): Set x = t; p = null; found = false; While (not found) and (x is not empty) { if k < key(x) descend left (i.e. set p = x; x = x left ) else if k > key(x) descend right (i.e. set p = x;x = x right ) else found = true } Notice that: P is null if (k) is in the root or if the tree is empty. If (k) is not found, p points to what should have been its parent.

28 Search for Parent of a Node To delete a node, we need to find its parent. To search for the parent (p) of a node (x) with key (k) in tree (t): Set x = t; p = null; found = false; While (not found) and (x is not empty) { if k < key(x) descend left (i.e. set p = x; x = x left ) else if k > key(x) descend right (i.e. set p = x;x = x right ) else found = true } Notice that: P is null if (k) is in the root or if the tree is empty. If (k) is not found, p points to what should have been its parent.

29 Algorithm to remove a Node Let k = key to remove its node t = pointer to root of tree x = location where k is found p = parent of a node sx = inorder successor of x s = child of x

30 Algorithm to remove a Node Remove (t,k) { Search for (k) and its parent; If not found, return; else it is found at (x) with parent at (p): Case (x) has two children: Find inorder successor (sx) and its parent (p); Copy contents of (sx) into (x); Change (x) to point to (sx); Now (x) has one or no children and (p) is its parent

31 Algorithm to remove a Node Case (x) has one or no children: Let (s) point to the child of (x) or null if there are no children; If p = null then set root to null; else if (x) is a left child of (p), set p left = s; else set p right = s; Now (x) is isolated and can be deleted delete (x); }

32 Example: Delete Root x p = null

33 Example: Delete Root x p sx

34 Example: Delete Root p x S = null

35 Example: Delete Root p x S = null

36 Example: Delete Root x null delete

37 5. Binary Search Tree ADT Elements: A BST consists of a collection of elements that are all of the same type. An element is composed of two parts: key of and data of Structure: A node in a BST has at most two subtrees. The key value in a node is larger than all the keys in its left subtree and smaller than all keys in its right subtree. Duplicate keys are not allowed.

38 Binary Search Tree ADT Data members rootpointer to the tree root Basic Operations binaryTreea constructor insertinserts an item emptychecks if tree is empty searchlocates a node given a key

39 Binary Search Tree ADT Basic Operations (continued) retrieveretrieves data given key traversetraverses a tree (In-Order) preorderpre-order traversal levelorderLevel-order traversal removeDelete node given key graphsimple graphical output

40 Node Specification // The linked structure for a node can be // specified as a Class in the private part of // the main binary tree class. class treeNode// Hidden from user { public: keyType key; // key dataType data;// Data treeNode *left;// left subtree treeNode *right;// right subtree }; // end of class treeNode declaration //A pointer to a node can be specified by a type: typedef treeNode * NodePointer; NodePointer root;

41 6. Template Class Specification Because node structure is private, all references to pointers are hidden from user This means that recursive functions with pointer parameters must be private. A public (User available) member function will have to call an auxiliary private function to support recursion. For example, to traverse a tree, the user public function will be declared as: void traverse ( ) const; and will be used in the form: BST.traverse ( );

42 Template Class Specification Such function will have to call a private traverse function: void traverse2 (NodePointer ) const; Therefore, the implementation of traverse will be: template void binaryTree ::traverse() const { traverse2(root); } Notice that traverse2 can support recursion via its pointer parameter

43 Template Class Specification For example, if we use in-order traversal, then the private traverse function will be implemented as: template void binaryTree ::traverse2 (NodePointer aRoot)const { if (aRoot != NULL) { // recursive in-order traversal traverse2 (aRoot->left); cout key << endl; traverse2 (aRoot->right); } } // end of private traverse

Prof. Amr Goneid, AUC44 Template Class Specification All similar functions will be implemented using the same method. For example: Public FunctionPrivate Function insert (key,data)insert2 (pointer,key,data) search(key)search2 (pointer,key) retrieve(key,data)retrieve2 (pointer,key,data) traverse( )traverse2 (pointer)

Prof. Amr Goneid, AUC45 BinaryTree.h // FILE: BinaryTree.h // DEFINITION OF TEMPLATE CLASS BINARY SEARCH // TREE #ifndef BIN_TREE_H #define BIN_TREE_H // Specification of the class template class binaryTree {

Prof. Amr Goneid, AUC46 BinaryTree.h public: // Public Member functions... // CREATE AN EMPTY TREE binaryTree(); // INSERT AN ELEMENT INTO THE TREE bool insert(const keyType &, const dataType &); // CHECK IF THE TREE IS EMPTY bool empty() const; // SEARCH FOR AN ELEMENT IN THE TREE bool search (const keyType &) const; // RETRIEVE DATA FOR A GIVEN KEY bool retrieve (const keyType &, dataType &) const;

Prof. Amr Goneid, AUC47 BinaryTree.h // TRAVERSE A TREE void traverse() const; // Iterative Pre-order Traversal void preorder () const; // Iterative Level-order Traversal void levelorder () const; // GRAPHIC OUTPUT void graph() const; // REMOVE AN ELEMENT FROM THE TREE void remove (const keyType &);

48 BinaryTree.h private: // Node Class class treeNode { public: keyType key; // key dataType data;// Data treeNode *left;// left subtree treeNode *right;// right subtree }; // end of class treeNode declaration typedef treeNode * NodePointer; // Data member.... NodePointer root;

49 BinaryTree.h // Private Member functions... // Searches a subtree for a key bool search2 ( NodePointer, const keyType &) const; //Searches a subtree for a key and retrieves data bool retrieve2 (NodePointer, const keyType &, dataType &) const; // Inserts an item in a subtree bool insert2 (NodePointer &, const keyType &, const dataType &);

50 BinaryTree.h // Traverses a subtree void traverse2 (NodePointer ) const; // Graphic output of a subtree void graph2 ( int, NodePointer ) const; // LOCATE A NODE CONTAINING ELEMENT AND ITS // PARENT void parentSearch( const keyType &k, bool &found, NodePointer &locptr, NodePointer &parent) const; }; #endif // BIN_TREE_H #include “binaryTree.cpp”

Prof. Amr Goneid, AUC51 7. Other Search Trees There are many other search trees that are balanced trees. Examples are: AVL Trees, Red-Black trees

52 Other Search Trees (AVL Tree) Named after its Russian inventors: Adel'son-Vel'skii and Landis (1962) An AVL tree is a binary search tree in which the heights of the right subtree and left subtree of the root differ by at most 1 the left subtree and the right subtree are themselves AVL trees

53 AVL Tree Notice that: N(h) = N(h-1) + N(h-2) + 1 h-1 h-2h