Fundamentals of Programming II Binary Search Trees

Slides:



Advertisements
Similar presentations
Chapter 12 Binary Search Trees
Advertisements

Computer Science 112 Fundamentals of Programming II Queues and Priority Queues.
Computer Science 112 Fundamentals of Programming II Array-Based Queues.
Computer Science C++ High School Level By Guillermo Moreno.
CS 171: Introduction to Computer Science II
Introduction to Data Structure, Fall 2006 Slide- 1 California State University, Fresno Introduction to Data Structure Chapter 10 Ming Li Department of.
CS 104 Introduction to Computer Science and Graphics Problems Data Structure & Algorithms (4) Data Structures 11/18/2008 Yang Song.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L12 (Chapter 20) Lists, Stacks,
Chapter 12 C Data Structures Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
Fundamentals of Python: From First Programs Through Data Structures
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.
Binary Search Trees Section Trees Trees are efficient Many algorithms can be performed on trees in O(log n) time. Searching for elements.
Binary Trees. Node structure Data A data field and two pointers, left and right.
Computer Science 112 Fundamentals of Programming II Expression Trees.
CSCE 3110 Data Structures & Algorithm Analysis Binary Search Trees Reading: Chap. 4 (4.3) Weiss.
Computer Science 112 Fundamentals of Programming II Introduction to Stacks.
Chapter 19 Implementing Trees and Priority Queues Fundamentals of Java.
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 ),
Chapter 19 Implementing Trees and Priority Queues Fundamentals of Java.
Binary Trees 2 Overview Trees. Terminology. Traversal of Binary Trees. Expression Trees. Binary Search Trees.
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.
Computer Science 112 Fundamentals of Programming II Interfaces and Implementations.
Starting at Binary Trees
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.
Binary Search Trees Nilanjan Banerjee. 2 Goal of today’s lecture Learn about Binary Search Trees Discuss the first midterm.
Topic 19 Binary Search Trees "Yes. Shrubberies are my trade. I am a shrubber. My name is 'Roger the Shrubber'. I arrange, design, and sell shrubberies."
Binary Search Tree Traversal Methods. How are they different from Binary Trees?  In computer science, a binary tree is a tree data structure in which.
Lecture – Searching a Tree Neil Ghani University of Strathclyde.
Binary Search Tree Qamar Abbas.
Computer Science 112 Fundamentals of Programming II Binary Search Trees.
Computer Science 112 Fundamentals of Programming II Implementation Strategies for Unordered Collections.
Computer Science 112 Fundamentals of Programming II Introduction to Trees.
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. 1 Chapter 19 Binary Search Trees.
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.
Week 10 - Friday.  What did we talk about last time?  Graph representations  Adjacency matrix  Adjacency lists  Depth first search.
Binary Search Trees (BST)
Rooted Tree a b d ef i j g h c k root parent node (self) child descendent leaf (no children) e, i, k, g, h are leaves internal node (not a leaf) sibling.
Copyright © 2012 Pearson Education, Inc. Chapter 20: Binary Trees.
Trees Ellen Walker CPSC 201 Data Structures Hiram College.
2014-T2 Lecture 27 School of Engineering and Computer Science, Victoria University of Wellington  Lindsay Groves, Marcus Frean, Peter Andreae, and Thomas.
Binary Tree Implementation. Binary Search Trees (BST) Nodes in Left subtree has smaller values Nodes in right subtree has bigger values.
Computer Science 112 Fundamentals of Programming II Iterators.
1 AVL Trees II Implementation. 2 AVL Tree ADT A binary search tree in which the balance factor of each node is 0, 1, of -1. Basic Operations Construction,
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 20: Binary Trees.
Chapter 12 – Data Structures
Trees Chapter 15.
CSCE 3110 Data Structures & Algorithm Analysis
CSCE 3110 Data Structures & Algorithm Analysis
Fundamentals of Programming II Introduction to Trees
Recursive Objects (Part 4)
Sections 8.7 – 8.8 Balancing a Binary Search Tree.
Fundamentals of Programming II Interfaces and Implementations
Binary Search Tree Chapter 10.
Section 8.1 Trees.
Trees.
Computer Science 112 Fundamentals of Programming II
Topic 18 Binary Search Trees
Revised based on textbook author’s notes.
Binary Tree and General Tree
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.
Stacks with Dynamic Memory
Trees.
Chapter 20: Binary Trees.
Trees.
Binary Tree Implementation
Trees Trees.
Binary Tree Implementation And Applications
Presentation transcript:

Fundamentals of Programming II Binary Search Trees Computer Science 112 Fundamentals of Programming II Binary Search Trees

Iterative Binary Search def index(target, sortedList): left = 0 right = len(sortedList) – 1 while left <= right: mid = (left + right) // 2 # compute midpoint if target == sortedList[mid]: return mid # found target elif target < sortedList[mid]: right = mid – 1 # go left else: left = mid + 1 # go right return -1 # target not there

Recursive Binary Search def index(target, sortedList): def recurse(left, right): if left > right: return -1 # target not there else: mid = (left + right) // 2 # compute midpoint if target == sortedList[mid]: return mid # found target elif target < sortedList[mid]: return recurse(left, mid – 1) # go left return recurse(mid + 1, right) # go right return recurse(0, len(sortedList) – 1)

Call Tree for Binary Search 34 41 56 63 72 89 95 0 1 2 3 4 5 6

Call Tree for Binary Search 34 41 56 63 72 89 95 0 1 2 3 4 5 6 72 89 95 34 41 56 4 5 6 0 1 2

Call Tree for Binary Search 34 41 56 63 72 89 95 0 1 2 3 4 5 6 72 89 95 34 41 56 4 5 6 0 1 2 72 95 34 56 4 6 0 2

Binary Search Tree (BST) 63 89 41 72 95 34 56

Binary Search Tree (BST) Ordering principle: Each item in the left subtree is less than the item in the parent Each item in the right subtree is greater than the item in the parent

Recursive Search of a BST Node contains(target, node) If the node is None Return False Else if node.data equals the target Return True Else if the target is less than the data Return contains(target, node.left) Else Return contains(target, node.right)

Minimal Set of BST Operations t.isEmpty() Returns True if empty, False otherwise len(t) Returns the number of items in the tree str(t) Returns a string representation iter(t) Supports a for loop, visiting in preorder item in t True if item is in tree, False otherwise t1 + t2 Returns a new tree with items in t1 and t2 t1 == t2 Equality test for two trees t.add(item) Adds item to the tree t.remove(item) Removes the given item The precondition of remove is that the item is in the tree.

Tree-Specific Operations t.preorder() Returns an iterator for preorder traversal t.inorder() Returns an iterator for inorder traversal t.postorder() Returns an iterator for postorder traversal t.levelorder() Returns an iterator for levelorder traversal t.height() Returns the number of links from the root to the deepest leaf t.isBalanced() Returns True if t.height() < 2 * log2(len(t) + 1) - 1 or False otherwise t.rebalance() Rearranges the nodes to ensure that t.height() <= log2(len(t) + 1)

Using a Binary Search Tree tree = LinkedBST() tree.add("D") tree.add("B") tree.add("A") tree.add("C") tree.add("F") tree.add("E") tree.add("G") print(tree) print("F" in tree) for item in tree: print(item) for item in tree.inorder(): print(item) for item in tree.postorder(): print(item) for item in tree.levelorder(): print(item) for ch in ('A', 'B', 'C', 'D', 'E', 'F', 'G'): print(tree.remove(ch))

The LinkedBST Class from abstractcollection import AbstractCollection from bstnode import BSTNode class LinkedBST(AbstractCollection): def __init__(self, sourceCollection = None): self._root = None AbstractCollection.__init__(self, sourceCollection) # Tree methods go here

Method __contains__ def __contains__(self, target): """Returns True if target is found or False otherwise.""” def recurse(node): if node is None: return False elif target == node.data: return True elif target < node.data : return recurse(node.left) else: return recurse(node.right) return recurse(self._root) Several operations call nested helper functions to recurse on nodes

Method __contains__ Alternatively, for the logically intoxicated . . . def __contains__(self, target): """Returns True if target is found or False otherwise.""” def recurse(node): return node != None and \ (target == node.data or \ (target < node.data and recurse(node.left)) or \ recurse(node.right)) return recurse(self._root) Alternatively, for the logically intoxicated . . .

Preorder Traversal def preorder(self): """Supports a preorder traversal on a view of self.""" lyst = list() def recurse(node): if node != None: lyst.append(node.data) recurse(node.left) recurse(node.right) recurse(self._root) return iter(lyst) A traversal a list of items in the order in which they were visited

iter – First Attempt The iterator captures a preorder traversal def __iter__(self): """Supports a preorder traversal on a view of self.""” self.preorder() The iterator captures a preorder traversal However, this implementation would incur linear running time and linear growth of memory before the caller ever accesses an item Moreover, mutations within the iterator are not detected

iter – Second Attempt If the tree is not empty Create a new stack Push the root node onto the stack While the stack is not empty Pop the top node and yield its data Check the mod count for mutation and respond if necessary If the node’s right subtree is not empty Push the right subtree onto the stack If the node’s left subtree is not empty Push the left subtree onto the stack Visits the nodes in preorder, yielding the datum in each node What is the running time and growth of memory?

Adding Items to a BST D New items are always added to the frontier of the tree, as leaf nodes B F A G

Case 1: The Tree is Empty Set the root to a new node containing the item

Case 2: The Tree Is Not Empty Search for the proper place for the new node D E B F A G

Case 2: The Tree Is Not Empty Search for the proper place for the new node D E B F A G

Case 2: The Tree Is Not Empty Search for the proper place for the new node D B F A E G

Method add def add(self, item): """Adds item to self.""" # Tree is empty, so new item goes at the root if self.isEmpty(): self._root = BSTNode(item) # Otherwise, search for the item's spot else: recurse(self._root) self._size += 1 Define a helper function recurse to perform the search for the new item’s place in a non-empty tree

Method add def add(self, item): """Adds item to self.""" def recurse(node): # New item is less, go left until spot is found if item < node.data: if node.left is None: node.left = BSTNode(item) else: recurse(node.left) # New item is >=, go right until spot is found elif node.right is None: node.right = BSTNode(item) recurse(node.right) # Tree is empty, so new item goes at the root if self.isEmpty(): self._root = BSTNode(item) # Otherwise, search for the item's spot recurse(self._root) self._size += 1

Method str Displays the tree rotated 90° counterclockwise def __str__(self): def recurse(node, level): s = "" if node != None: s += recurse(node.right, level + 1) s += "| " * level s += str(node.data) + "\n" s += recurse(node.left, level + 1) return s return recurse(self._root, 0) Displays the tree rotated 90° counterclockwise

Adding Items in Best Order tree = LinkedBST() print(">>>>Items in advantageous order:") tree.add("E") tree.add("C") tree.add("D") tree.add("A") tree.add("H") tree.add("F") tree.add("K") print(tree)

Adding Items in Worst Order print(">>>>Items in worst order:") tree = LinkedBST() for i in range(1, 9): tree.add(i) print(tree)

Adding Items in Random Order print(">>>>Items in random order:") tree = LinkedBST() for i in range(7): tree.add(randomString()) print(tree)

Performance A D Best B C F C A B E G D Worst E F G

The Shape of the Tree As the tree becomes linear, searches and insertions degrade to linear A BST can be rebalanced in linear time Alternatively, a BST can be set up to maintain its balance during insertions

Parsing Expressions with Recursive Descent For Wednesday Parsing Expressions with Recursive Descent