CMPSCI 187: Programming With Data Structures. Lecture #26: Binary Search Trees David Mix Barrington 9 November 2012

Similar documents
Binary Trees, Binary Search Trees

Programming II (CS300)

CmpSci 187: Programming with Data Structures Spring 2015

Binary Trees

March 20/2003 Jayakanth Srinivasan,

Data Structures. Trees. By Dr. Mohammad Ali H. Eljinini. M.A. Eljinini, PhD

Programming II (CS300)

TREES. Trees - Introduction

Advanced Java Concepts Unit 5: Trees. Notes and Exercises

Section 5.5. Left subtree The left subtree of a vertex V on a binary tree is the graph formed by the left child L of V, the descendents

Trees. (Trees) Data Structures and Programming Spring / 28

Data Structures and Algorithms for Engineers

Trees. CSE 373 Data Structures

Trees! Ellen Walker! CPSC 201 Data Structures! Hiram College!

MULTIMEDIA COLLEGE JALAN GURNEY KIRI KUALA LUMPUR

INF2220: algorithms and data structures Series 1

CSI33 Data Structures

Tree: non-recursive definition. Trees, Binary Search Trees, and Heaps. Tree: recursive definition. Tree: example.

Chapter 20: Binary Trees

CE 221 Data Structures and Algorithms

Lec 17 April 8. Topics: binary Trees expression trees. (Chapter 5 of text)

Data Structure Lecture#10: Binary Trees (Chapter 5) U Kang Seoul National University

Binary Trees. College of Computing & Information Technology King Abdulaziz University. CPCS-204 Data Structures I

! Tree: set of nodes and directed edges. ! Parent: source node of directed edge. ! Child: terminal node of directed edge

TREES Lecture 12 CS2110 Spring 2018

Data Structures Question Bank Multiple Choice

Associate Professor Dr. Raed Ibraheem Hamed

ECE 242. Data Structures

Garbage Collection: recycling unused memory

Binary Trees. BSTs. For example: Jargon: Data Structures & Algorithms. root node. level: internal node. edge.

CS350: Data Structures Tree Traversal

! Tree: set of nodes and directed edges. ! Parent: source node of directed edge. ! Child: terminal node of directed edge

CMSC 341 Lecture 10 Binary Search Trees

Programming II (CS300)

Trees, Binary Trees, and Binary Search Trees

Advanced Java Concepts Unit 5: Trees. Notes and Exercises

CISC 235 Topic 3. General Trees, Binary Trees, Binary Search Trees

IX. Binary Trees (Chapter 10)

Chapter 4 Trees. Theorem A graph G has a spanning tree if and only if G is connected.

Stacks, Queues and Hierarchical Collections

Trees : Part 1. Section 4.1. Theory and Terminology. A Tree? A Tree? Theory and Terminology. Theory and Terminology

Name CPTR246 Spring '17 (100 total points) Exam 3

Data Structure. IBPS SO (IT- Officer) Exam 2017

Friday Four Square! 4:15PM, Outside Gates

Lecture Notes 16 - Trees CSS 501 Data Structures and Object-Oriented Programming Professor Clark F. Olson

CS301 - Data Structures Glossary By

Discussion 2C Notes (Week 8, February 25) TA: Brian Choi Section Webpage:

Cpt S 122 Data Structures. Data Structures Trees

Binary Search Trees Treesort

Why Do We Need Trees?

Bioinformatics Programming. EE, NCKU Tien-Hao Chang (Darby Chang)

Data Structure - Binary Tree 1 -

1 Binary trees. 1 Binary search trees. 1 Traversal. 1 Insertion. 1 An empty structure is an empty tree.

Data Structures And Algorithms

Introduction to Computers and Programming. Concept Question

Trees Chapter 19, 20. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

CSCI-401 Examlet #5. Name: Class: Date: True/False Indicate whether the sentence or statement is true or false.

Data Structures and Algorithms

Computational Optimization ISE 407. Lecture 16. Dr. Ted Ralphs

Lecture 26. Introduction to Trees. Trees

Stacks, Queues and Hierarchical Collections. 2501ICT Logan

CS61B Lecture #20: Trees. Last modified: Mon Oct 8 21:21: CS61B: Lecture #20 1

Trees. Q: Why study trees? A: Many advance ADTs are implemented using tree-based data structures.

Chapter Contents. Trees. Tree Concepts. Hierarchical Organization. Hierarchical Organization. Hierarchical Organization.

7.1 Introduction. A (free) tree T is A simple graph such that for every pair of vertices v and w there is a unique path from v to w

Spring 2018 Mentoring 8: March 14, Binary Trees

ITI Introduction to Computing II

Abstract Data Structures IB Computer Science. Content developed by Dartford Grammar School Computer Science Department

Computer Science 210 Data Structures Siena College Fall Topic Notes: Trees

Trees. Truong Tuan Anh CSE-HCMUT

Tree. A path is a connected sequence of edges. A tree topology is acyclic there is no loop.

Trees 11/15/16. Chapter 11. Terminology. Terminology. Terminology. Terminology. Terminology

Trees. Dr. Ronaldo Menezes Hugo Serrano Ronaldo Menezes, Florida Tech

COMP : Trees. COMP20012 Trees 219

Advanced Tree Data Structures

Binary Search Tree (2A) Young Won Lim 5/17/18

Cpt S 122 Data Structures. Course Review Midterm Exam # 1

Todays Lecture. Assignment 2 deadline: You have 5 Calendar days to complete.

Partha Sarathi Mandal

Trees. Introduction & Terminology. February 05, 2018 Cinda Heeren / Geoffrey Tien 1

Recursive Data Structures and Grammars

ITI Introduction to Computing II

Principles of Computer Science

MID TERM MEGA FILE SOLVED BY VU HELPER Which one of the following statement is NOT correct.

Analysis of Algorithms

Trees, Part 1: Unbalanced Trees

Chapter 11.!!!!Trees! 2011 Pearson Addison-Wesley. All rights reserved 11 A-1

Chapter 11.!!!!Trees! 2011 Pearson Addison-Wesley. All rights reserved 11 A-1


DATA STRUCTURES AND ALGORITHMS. Hierarchical data structures: AVL tree, Bayer tree, Heap

CS24 Week 8 Lecture 1

Trees. A tree is a directed graph with the property

Why Use Binary Trees? Data Structures - Binary Trees 1. Trees (Contd.) Trees

Summer Final Exam Review Session August 5, 2009

CS 171: Introduction to Computer Science II. Binary Search Trees

If you took your exam home last time, I will still regrade it if you want.

Trees. Trees. CSE 2011 Winter 2007

4/18/ Binary Search Trees (BSTs) 17.1 Adding an Element to a BST Removing an Element from a BST. 17.

CMPSCI 187: Programming With Data Structures. Lecture #28: Binary Search Trees 21 November 2011

Data Structures - Binary Trees 1

Transcription:

CMPSCI 187: Programming With Data Structures Lecture #26: Binary Search Trees David Mix Barrington 9 November 2012

Binary Search Trees Why Binary Search Trees? Trees, Binary Trees and Vocabulary The BST Rule Traversals The BSTInterface An Application Example Beginning the Implementation

Why Binary Search Trees? We ve seen that binary search is a powerful technique to search sorted arrays, finding an element in O(log n) time rather than O(n) for linear search. But inserting or deleting into arrays is in general O(n) due to shifting elements. Linked structures are good for inserting and deleting quickly, once you have a pointer to the place where it is happening, but they don t allow the random access to arbitrary elements that we need to do binary search. We could speed up our access to the middle elements of a linked list by adding more pointers, say from the beginning of the list to the middle, or from the middle to the three-quarters mark. Doing this right, we can add the abilities we need to get to the element we want in O(log n) time. The best way to arrange this sort of thing turns out to be a tree structure.

Trees, Binary Trees, and Vocabulary We ve seen trees in the directory structures of operating systems, in the organization of a textbook or a company, and in Discussion #6 where we wrote a recursive method to compare binary trees for equality. A binary tree is one where each node may have a left child or a right child or both. There is one node called the root, and every node except for the root is the child of another node. A leaf is a node with no children. We use genealogical language to describe trees: parent, ancestor, descendant, sometimes even uncle or niece. We say that the root node of a tree is at level 0, its children are at level 1, its grandchildren at level 2, and so forth. The highest level of any node in the tree is the tree s height.

The BST Rule A binary search tree is a binary tree with an element, from some class T that has a compareto method defined, at every node. The BST Rule is that for every node x, the element at x is greater than the elements in x s left child and all descendants of the left child, and is less than the elements in x s right child and all descendants of the right child. Thus x s element splits the smaller values in the left subtree from the greater values in the right subtree. This allows us to find an arbitrary element by a form of binary search. We look at the root. If it is our target we win, and if not we recurse to the root s left child (if the target is smaller than the root s element) or to its right child (if the target is greater). If the element is there we will find it this way, with a number of tries bounded by the height of the tree. If it is not there, we will find out when we recurse to a node that is null.

Traversals Just as we had prefix, infix, and postfix strings to represent formulas, we have three ways to traverse the nodes of a binary tree in order: preorder, inorder, and postorder. If our tree is the parse tree of a formula with binary operators and values at the leaves, each order gives the order of the characters in the corresponding string. Each traversal is defined recursively, so that we define how to visit each node. Visiting a node means processing it in some way, and our recursive definition of traversing a node x will give us a way to visit all the nodes in the subtree under x (x and all its descendants). A preorder traversal of x first visits x, then traverses its left child, then traverses its right child. An inorder traversal traverses the left child, visits the node, and traverses the right child. A postorder traversal traverses the left child, traverses the right child, and finally visits the node.

The BSTInterface The basic operations of a BST are exactly those of a list. The main difference (and the reason we don t just extend) is that the reset and getnext operations take a parameter. There are three different current positions, one for each type of traversal. public interface BSTInterface<T extends Comparable<T>> { static final int INORDER = 1, PREORDER = 2, POSTORDER = 3; boolean isempty( ); int size( ); boolean contains (T element); boolean remove (T element); T get (T element); void add (T element); int reset (int ordertype); T getnext (int ordertype);}

An Application Example public class GolfApp2 { public static void main (String [ ] args) { Scanner conin = new Scanner(System.in); String name; int score; BSTInterface<Golfer> golfers = new BinarySearchTree<Golfer>( ); Golfer golfer; int numgolfers; String skip; System.out.println( Golfer name (press Enter to end): ); name = conin.nextline( ); while (!name.equals( )) { System.out.println( Score: ); score = conin.nextline( ); skip = conin.nextline( ); golfer = new Golfer (name, score); golfers.add(golfer); System.out.println( Name: ); name = conin.nextline( );} System.out.println( The final results are: ); numgolfers = golfers.reset(binarysearchtree.inorder); for (int i = 1; i <= numgolfers; i++) { System.out.println(golfers.getNext(BST.INORDER);}}}

Beginning the Implementation Like a list, a tree is a linked structure whose nodes are allocated dynamically. We begin by defining a class for the nodes, which looks a lot like the classes for singly or doubly linked lists. Note that any binary tree with elements at every node could use a similar type of node -- this is a search tree node because T must be a class that supports the compareto method. public class BSTNode<T extends Comparable<T>> { protected T info; protected BSTNode left; protected BSTNode right; public BSTNode (T info) { this.info = info; left = right = null;} // getters and setters }

The BinarySearchTree Class You would think that we would keep a current position for each of the three types of traversals, but instead the reset operation will make a queue of all the elements, in the correct order, and the getnext method will just dequeue and return the next queue element. public class BinarySearchTree<T extends Comparable<T>> implements BSTInterface<T> { protected BSTNode root; boolean found; // used by remove protected LinkUnbndQueue<T> inorderqueue; // for traversal protected LinkUnbndQueue<T> preorderqueue; // ditto protected LinkUnbndQueue<T> postorderqueue; // ditto public BinarySearchTree( ) { root = null;} public boolean isempty( ) { return (root == null);} // more methods to come next lecture!