(c) 1997-2003 University of Washington20c-1 CSC 143 Binary Search Trees.

Slides:



Advertisements
Similar presentations
CS16: Introduction to Data Structures & Algorithms
Advertisements

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.
Trees Types and Operations
S. Sudarshan Based partly on material from Fawzi Emad & Chau-Wen Tseng
Course: Programming II - Abstract Data Types ADT Binary Search TreeSlide Number 1 The ADT Binary Search Tree Definition The ADT Binary Search Tree is a.
Binary Trees, Binary Search Trees COMP171 Fall 2006.
Binary Search Trees Briana B. Morrison Adapted from Alan Eugenio.
Department of Computer Science University of Maryland, College Park
1 Trees. 2 Outline –Tree Structures –Tree Node Level and Path Length –Binary Tree Definition –Binary Tree Nodes –Binary Search Trees.
CSE 143 Lecture 19 Binary Search Trees read 17.3 slides created by Marty Stepp
1 Joe Meehean.  Important and common problem  Given a collection, determine whether value v is a member  Common variation given a collection of unique.
By : Budi Arifitama Pertemuan ke Objectives Upon completion you will be able to: Create and implement binary search trees Understand the operation.
CSCE 3110 Data Structures & Algorithm Analysis Binary Search Trees Reading: Chap. 4 (4.3) Weiss.
Trees, Binary Search Trees, Recursion, Project 2 Bryce Boe 2013/08/01 CS24, Summer 2013 C.
Chapter 19 - basic definitions - order statistics ( findkth( ) ) - balanced binary search trees - Java implementations Binary Search Trees 1CSCI 3333 Data.
Data Structures - CSCI 102 Binary Tree In binary trees, each Node can point to two other Nodes and looks something like this: template class BTNode { public:
Recursion Bryce Boe 2013/11/18 CS24, Fall Outline Wednesday Recap Lab 7 Iterative Solution Recursion Binary Tree Traversals Lab 7 Recursive Solution.
Building Java Programs Binary Search Trees; TreeSet.
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,
S EARCHING AND T REES COMP1927 Computing 15s1 Sedgewick Chapters 5, 12.
BINARY SEARCH TREE. Binary Trees A binary tree is a tree in which no node can have more than two children. In this case we can keep direct links to the.
Binary Trees, Binary Search Trees RIZWAN REHMAN CENTRE FOR COMPUTER STUDIES DIBRUGARH UNIVERSITY.
1 Binary Trees Informal defn: each node has 0, 1, or 2 children Informal defn: each node has 0, 1, or 2 children Formal defn: a binary tree is a structure.
Binary Search Trees Binary Search Trees (BST)  the tree from the previous slide is a special kind of binary tree called a binary.
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.
Binary Search Trees Nilanjan Banerjee. 2 Goal of today’s lecture Learn about Binary Search Trees Discuss the first midterm.
 Trees Data Structures Trees Data Structures  Trees Trees  Binary Search Trees Binary Search Trees  Binary Tree Implementation Binary Tree Implementation.
Red–black trees.  Define the red-black tree properties  Describe and implement rotations  Implement red-black tree insertion  We will skip red-black.
Lec 15 Oct 18 Binary Search Trees (Chapter 5 of text)
CSE 143 Lecture 22 Binary Search Trees continued; Tree Sets read slides adapted from Marty Stepp and Hélène Martin
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.
Binary Search Trees (BSTs) 18 February Binary Search Tree (BST) An important special kind of binary tree is the BST Each node stores some information.
CSE 143 Lecture 21 Binary Search Trees, continued read slides created by Marty Stepp
1/14/20161 BST Operations Data Structures Ananda Gunawardena.
Binary Search Trees (BST)
Tree Data Structures. Heaps for searching Search in a heap? Search in a heap? Would have to look at root Would have to look at root If search item smaller.
Trees. 2 Root leaf CHAPTER 5 3 Definition of Tree n A tree is a finite set of one or more nodes such that: n There is a specially designated node called.
COSC 2007 Data Structures II Chapter 13 Advanced Implementation of Tables I.
2014-T2 Lecture 27 School of Engineering and Computer Science, Victoria University of Wellington  Lindsay Groves, Marcus Frean, Peter Andreae, and Thomas.
1 Joe Meehean. A A B B D D I I C C E E X X A A B B D D I I C C E E X X  Terminology each circle is a node pointers are edges topmost node is the root.
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,
CSE 143 Lecture 20 Binary Search Trees read 17.3 slides created by Marty Stepp
(c) University of Washington20-1 CSC 143 Java Trees.
CSCE 3110 Data Structures & Algorithm Analysis
CSCE 3110 Data Structures & Algorithm Analysis
CSE 373 Binary search trees; tree height and balance
CSC 427: Data Structures and Algorithm Analysis
Efficiency of in Binary Trees
UNIT III TREES.
CISC220 Fall 2009 James Atlas Lecture 13: Binary Trees.
Binary Search Tree (BST)
Trees.
COMP 103 Binary Search Trees.
Chapter 22 : Binary Trees, AVL Trees, and Priority Queues
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.
Monday, April 16, 2018 Announcements… For Today…
CMSC 341 Lecture 10 B-Trees Based on slides from Dr. Katherine Gibson.
Lec 12 March 9, 11 Mid-term # 1 (March 21?)
Find in a linked list? first last 7  4  3  8 NULL
CSE 373: Data Structures and Algorithms
Lecture 12 CS203 1.
Binary Search Trees Chapter 9 2/22/2019 B.Ramamurthy.
Binary Trees, Binary Search Trees
CSE 373 Data Structures and Algorithms
CSC 143 Java Trees.
CSC 143 Binary Search Trees.
Trees.
Binary Trees, Binary Search Trees
Tree (new ADT) Terminology: A tree is a collection of elements (nodes)
Presentation transcript:

(c) University of Washington20c-1 CSC 143 Binary Search Trees

(c) University of Washington20c-2 Costliness of contains Review: in a binary tree, contains is O(N) contains may be a frequent operation in an application Can we do better than O(N)? Turn to list searching for inspiration... Why was binary search so much better than linear search? Can we apply the same idea to trees?

(c) University of Washington20c-3 Binary Search Trees Idea: order the nodes in the tree so that, given that a node contains a value v, All nodes in its left subtree contain values <= v All nodes in its right subtree contain values >= v A binary tree with these properties is called a binary search tree (BST)

(c) University of Washington20c-4 Examples(?) Are these are binary search trees? Why or why not?

(c) University of Washington20c-5 Implementing a Set with a BST Can exploit properties of BSTs to have fast, divide-and- conquer implementations of Set's add and contains operations TreeSet! A TreeSet can be represented by a pointer to the root node of a binary search tree, or null of no elements yet public class SimpleTreeSet implements Set { private BTNode root ;// root node, or null if none public SimpleTreeSet ( ) { this.root = null; } // size as for BinTree … }

(c) University of Washington20c-6 contains for a BST Original contains had to search both subtrees Like linear search With BSTs, can only search one subtree! All small elements to the left, all large elements to the right Search either left or right subtree, based on comparison between elem and value at root of tree Like binary search

(c) University of Washington20c-7 Code for contains (in TreeSet) /** Return whether elem is in set */ public boolean contains (Object elem) { return subtreeContains(root, (Comparable)elem); } // Return whether elem is in (sub-)tree with root n private boolean subtreeContains (BTNode n, Comparable elem) { if (n == null) { return false; } else { int comp = elem.compareTo(n.item); if (comp == 0) { return true; }// found it! else if (comp < 0) { return subtreeContains(n.left, elem); }// search left else /* comp > 0 */ { return subtreeContains(n. right, elem); }// search right }

(c) University of Washington20c-8 Examples contains(6) root contains(10) root

(c) University of Washington20c-9 Cost of BST contains Work done at each node: Number of nodes visited (depth of recursion): Total cost:

(c) University of Washington20c-10 add Must preserve BST invariant: insert new element in correct place in BST Two base cases Tree is empty: create new node which becomes the root of the tree If node contains the value, found it; suppress duplicate add Recursive case Compare value to current node’s value If value < current node's value, add to left subtree recursively Otherwise, add to right subtree recursively

(c) University of Washington20c-11 Example Add 8, 10, 5, 1, 7, 11 to an initially empty BST, in that order:

(c) University of Washington20c-12 Example (2) What if we change the order in which the numbers are added? Add 1, 5, 7, 8, 10, 11 to a BST, in that order (following the algorithm):

(c) University of Washington20c-13 Code for add (in TreeSet) /** Ensure that elem is in the set. Return true if elem was added, false otherwise. */ public boolean add (Object elem) { try { BTNode newRoot = addToSubtree(root, (Comparable)elem);// add elem to tree root = newRoot;// update root to point to new root node return true;// return true (tree changed) } catch (DuplicateAdded e) { // detected a duplicate addition return false;// return false (tree unchanged) } /** Add elem to tree rooted at n. Return (possibly new) tree containing elem, or throw DuplicateAdded if elem already was in tree */ private BTNode addToSubtree (BTNode n, Comparable elem) throws DuplicateAdded { … }

(c) University of Washington20c-14 Code for addToSubtree /** Add elem to tree rooted at n. Return (possibly new) tree containing elem, or throw DuplicateAdded if elem already was in tree */ private BTNode addToSubtree (BTNode n, Comparable elem) throws DuplicateAdded { if (n == null) { return new BTNode(elem, null, null); }// adding to empty tree int comp = elem.compareTo(n.item); if (comp == 0) { throw new DuplicateAdded( ); }// elem already in tree if (comp < 0) {// add to left subtree BTNode newSubtree = addToSubtree(n.left, elem); n.left = newSubtree;// update left subtree } else /* comp > 0 */ {// add to right subtree BTNode newSubtree = addToSubtree(n.right, elem); n.right = newSubtree;// update right subtree } return n;// this tree has been modified to contain elem }

(c) University of Washington20c-15 Cost of add Cost at each node: How many recursive calls? Proportional to height of tree Best case? Worst case?

(c) University of Washington20c-16 A Challenge: iterator How to return an iterator that traverses the sorted set in order? Need to iterate through the items in the BST, from smallest to largest Problem: how to keep track of position in tree where iteration is currently suspended Need to be able to implement next( ), which advances to the correct next node in the tree Solution: keep track of a path from the root to the current node Still some tricky code to find the correct next node in the tree

(c) University of Washington20c-17 Another Challenge: remove Algorithm: find the node containing the element value being removed, and remove that node from the tree Removing a leaf node is easy: replace with an empty tree Removing a node with only one non-empty subtree is easy: replace with that subtree How to remove a node that has two non-empty subtrees? Need to pick a new element to be the new root node, and adjust at least one of the subtrees E.g., remove the largest element of the left subtree (will be one of the easy cases described above), make that the new root

(c) University of Washington20c-18 Analysis of Binary Search Tree Operations Cost of operations is proportional to height of tree Best case: tree is balanced Depth of all leaf nodes is roughly the same Height of a balanced tree with n nodes is ~log 2 n If tree is unbalanced, height can be as bad as the number of nodes in the tree Tree becomes just a linear list

(c) University of Washington20c-19 Summary A binary search tree is a good general implementation of a set, if the elements can be ordered Both contains and add benefit from divide-and-conquer strategy No sliding needed for add Good properties depend on the tree being roughly balanced Open issues (or, why take a data structures course?) How are other operations implemented (e.g. iterator, remove)? Can you keep the tree balanced as items are added and removed?