Binary Search Trees Chapter 6.

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.
Binary Trees Chapter 6. Linked Lists Suck By now you realize that the title to this slide is true… By now you realize that the title to this slide is.
1 Breadth First Traversal. 2 Objectives You will be able to Do a breadth first traversal of a binary tree. Display a binary tree in its normal (vertical)
Binary Trees, Binary Search Trees CMPS 2133 Spring 2008.
1 Binary Search Trees II Chapter 6. 2 Objectives You will be able to use a binary search tree template with your own classes.
Binary Trees, Binary Search Trees COMP171 Fall 2006.
CS 171: Introduction to Computer Science II
Trees, Binary Trees, and Binary Search Trees COMP171.
1 Trees. 2 Outline –Tree Structures –Tree Node Level and Path Length –Binary Tree Definition –Binary Tree Nodes –Binary Search Trees.
Gordon College Prof. Brinton
© 2006 Pearson Addison-Wesley. All rights reserved11 A-1 Chapter 11 Trees.
1 abstract containers hierarchical (1 to many) graph (many to many) first ith last sequence/linear (1 to 1) set.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 19 Binary.
CS21, Tia Newhall Binary Search Trees (BST) 1.Hierarchical data structure with a single pointer to root node 2.Each node has at most two child nodes (a.
10. Binary Trees A. Introduction: Searching a linked list.
Binary Search Trees Chapter 7 Objectives
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.
Binary Trees Chapter 6.
Version TCSS 342, Winter 2006 Lecture Notes Trees Binary Trees Binary Search Trees.
1 Binary Search Trees III Delete Chapter 6. 2 Objectives You will be able to write code to delete a node from a Binary Search Tree.
By : Budi Arifitama Pertemuan ke Objectives Upon completion you will be able to: Create and implement binary search trees Understand the operation.
Data Structures Arrays both single and multiple dimensions Stacks Queues Trees Linked Lists.
Binary Tree. Binary Trees – An Informal Definition A binary tree is a tree in which no node can have more than two children Each node has 0, 1, or 2 children.
Trees Chapter 8. 2 Tree Terminology A tree consists of a collection of elements or nodes, organized hierarchically. The node at the top of a tree is called.
Advanced Algorithms Analysis and Design Lecture 8 (Continue Lecture 7…..) Elementry Data Structures By Engr Huma Ayub Vine.
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,
Lecture 10 Trees –Definiton of trees –Uses of trees –Operations on a tree.
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.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Searching:
A Binary Search Tree Binary Search Trees.
Chapter 6 Binary Trees. 6.1 Trees, Binary Trees, and Binary Search Trees Linked lists usually are more flexible than arrays, but it is difficult to use.
Tree (new ADT) Terminology:  A tree is a collection of elements (nodes)  Each node may have 0 or more successors (called children)  How many does a.
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.
Trees, Binary Trees, and Binary Search Trees COMP171.
Computer Science: A Structured Programming Approach Using C Trees Trees are used extensively in computer science to represent algebraic formulas;
 Trees Data Structures Trees Data Structures  Trees Trees  Binary Search Trees Binary Search Trees  Binary Tree Implementation Binary Tree Implementation.
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.
Binary trees Binary search trees Expression trees Heaps Data Structures and Algorithms in Java, Third EditionCh06 – 1.
Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Modified for use at Midwestern State University Chapter.
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.
CSE 3358 NOTE SET 10 Data Structures and Algorithms.
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.
1 Chapter 7 Objectives Upon completion you will be able to: Create and implement binary search trees Understand the operation of the binary search tree.
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 Chapter 4 Trees Basic concept How tree are used to implement the file system How tree can be used to evaluate arithmetic expressions How to use trees.
ADT Binary Search Tree Ellen Walker CPSC 201 Data Structures Hiram College.
Lecture - 11 on Data Structures. Prepared by, Jesmin Akhter, Lecturer, IIT,JU Threaded Trees Binary trees have a lot of wasted space: the leaf nodes each.
Trees Namiq Sultan. Trees Trees are very flexible, versatile and powerful non-liner data structure that can be used to represent data items possessing.
CHAPTER 5 TREE CSEB324 DATA STRUCTURES & ALGORITHM.
Data Structures: A Pseudocode Approach with C, Second Edition 1 Chapter 7 Objectives Create and implement binary search trees Understand the operation.
Binary Tree Implementation. Binary Search Trees (BST) Nodes in Left subtree has smaller values Nodes in right subtree has bigger values.
BINARY TREES Objectives Define trees as data structures Define the terms associated with trees Discuss tree traversal algorithms Discuss a binary.
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.
1 Trees. 2 Trees Trees. Binary Trees Tree Traversal.
Binary Search Trees Chapter 7 Objectives
Trees Chapter 15.
Searching and Binary Search Trees
Binary Search Tree (BST)
Binary Trees, Binary Search Trees
Chapter 20: Binary Trees.
Chapter 21: Binary Trees.
Searching: Binary Trees
Binary Trees, Binary Search Trees
Heaps and priority queues
Binary Trees, Binary Search Trees
Data Structures Using C++ 2E
Chapter 11 Trees © 2011 Pearson Addison-Wesley. All rights reserved.
Presentation transcript:

Binary Search Trees Chapter 6

Implement and use binary search trees in C++ programs. Objectives You will be able to Implement and use binary search trees in C++ programs. Determine the time complexity of searching binary search trees.

We often need to find a specific item in a collection of items. Searching We often need to find a specific item in a collection of items. Or determine that it is not present. The simplest strategy is a linear search. Traverse the collection looking for the target item. Time for a linear search is O(n). Grows in proportion to the number of items in the collection, n.

If length of the array is 0, Check the middle item. Binary Search If an array is ordered, we can make the search much faster by doing a binary search. If length of the array is 0, Search target is not present. Report failure. Check the middle item. If search target is equal Return that item. If the search target is less: Do a binary search of the lower half. If the search target greater Do a binary search of the upper half.

Usually outperforms a linear search Disadvantage: Binary Search Usually outperforms a linear search Disadvantage: Requires a sequential storage Not appropriate for linked lists (Why?) A linked structure is desirable if we do very much inserting and deleting. It is possible to use a linked structure which can be searched in a binary-like manner.

Binary Search Tree Everything in left subtree is less than root. 49 80 62 35 13 66 28 Everything in left subtree is less than root. Everything in right subtree is greater than root. Recursively!

Tree A data structure which consists of If the tree is nonempty -- a finite set of elements called nodes or vertices. a finite set of directed arcs which connect the nodes. If the tree is nonempty -- One of the nodes (the root) has no incoming arc. Every other node can be reached by following a unique sequence of consecutive arcs starting at the root.

Tree Terminology Root node Children of the parent (3) Siblings to each other Leaf nodes

Binary Tree Each node has at most two children Examples Results of multiple coin tosses Encoding/decoding messages in dots and dashes such as Morse code

Implementation A binary tree ADT can be implemented either as a linked structure or as an array.

Array Implementation of Binary Trees U P E C T M 2 1 6 5 4 3 Store node n in location n of the array.

Array Implementation of Binary Trees Works OK for complete trees, not for sparse trees

Linked Implementation of Binary Trees Uses space more efficiently for incomplete trees Provides additional flexibility Each node has two links One to the left child of the node One to the right child of the node If no child node exists for a node, the link is set to NULL

Structural Recursion The subset of a binary tree consisting of any node an all of its descendents is a binary tree. O U P E C T M 2 1 6 5 4 3 Invites the use of recursive algorithms on binary trees.

Recursive Algorithm for Binary Tree Traversal The "anchor" If the binary tree is empty Do nothing Else N: Visit the Node, process data L: Traverse the left subtree R: Traverse the right subtree The inductive step

Binary Tree Traversal Order Three possibilities for inductive step … Left subtree, Node, Right subtree Inorder traversal Node, Left subtree, Right subtree the preorder traversal Left subtree, Right subtree, Node the postorder traversal

Binary Search Tree A Collection of Nodes For each node x Binary Search Tree ADT Binary Search Tree A Collection of Nodes Data Must have <= and == operations Left Child Right Child For each node x value in left child ≤ value in x ≤ value in right child

Determine if BST is empty Search BST for given item BST Basic Operations Construct an empty BST Determine if BST is empty Search BST for given item Insert a new item in the BST Maintain the BST property Delete an item from the BST Traverse the BST Visit each node exactly once The inorder traversal will visit the values in the nodes in ascending order

Create new empty C++ console application project. Add to project: Example Create new empty C++ console application project. Add to project: genBST1.h main.cpp

Build and test. main.cpp #include <iostream> #include "genBST1.h" using namespace std; int main(void) { cout << "This is BST_Demo\n"; cin.get(); return 0; } Build and test.

Copy from Downloads area: genBST1.h Copy from Downloads area: http://www.cse.usf.edu/~turnerr/Data_Structures/Downloads/2011_03_02_Binary_Search_Tree/genBST1.h.txt This is a subset of Drozdek’s genBST.h template. Figure 6.8, page 221 ff. All textbook examples are available on the author's web site: http://www.mathcs.duq.edu/drozdek/DSinCpp/

BSTNode //************************ genBST1.h ************************** // generic binary search tree #pragma once; template<class T> class BSTNode { public: BSTNode() left = right = 0; } BSTNode(const T& el, BSTNode *l = 0, BSTNode *r = 0) key = el; left = l; right = r; T key; BSTNode *left, *right; };

Class BST template<class T> class BST { public: BST() {root = 0;} ~BST() {clear();} void clear() // Overloaded clear(root); root = 0; } bool isEmpty() const {return root == 0;} void insert(const T&); T* search(const T& el) const // Overloaded return search(root, el);

Class BST protected: BSTNode<T>* root; void clear(BSTNode<T>*); T* search(BSTNode<T>*, const T&) const; //void preorder(BSTNode<T>*); //void inorder(BSTNode<T>*); //void postorder(BSTNode<T>*); //virtual void visit(BSTNode<T>* p) { // cout << p->key << ' '; //} };

BST<T>::clear() template<class T> void BST<T>::clear(BSTNode<T> *p) { if (p != 0) clear(p->left); clear(p->right); delete p; }

BST<T>::insert() template<class T> void BST<T>::insert(const T& el) { BSTNode<T> *p = root, *prev = 0; // find a place for inserting new node; while (p != 0) prev = p; if (p->key < el) p = p->right; } else p = p->left;

BST<T>::insert() if (root == 0) // tree is empty; { root = new BSTNode<T>(el); } else if (prev->key < el) prev->right = new BSTNode<T>(el); else prev->left = new BSTNode<T>(el);

BST<T>::search() template<class T> T* BST<T>::search(BSTNode<T>* p, const T& el) const { while (p != 0) if (el == p->key) return &p->key; } if (el < p->key) p = p->left; else p = p->right; return 0; // el was not found

Test BST Template #include <iostream> #include "genBST1.h" using namespace std; int main(void) { cout << "This is BST_Demo\n"; BST<int> my_BST; my_BST.insert(13); my_BST.insert(10); my_BST.insert(25); my_BST.insert(2); my_BST.insert(12); my_BST.insert(20); my_BST.insert(31); my_BST.insert(29);

Test BST Template cout << "Items in the tree: "; for (int i = 0; i < 100; ++i) { int* result = my_BST.search(i); if (result != 0) cout << i << " "; } cout << endl; cin.get(); return 0;

Test Running End of presentation