Binary Trees Like a list, a (binary) tree can be empty or non-empty. In class we will explore a state-based implementation, similar to the LRS You are.

Slides:



Advertisements
Similar presentations
Chapter 7. Binary Search Trees
Advertisements

Binary Search Tree Smt Genap
Treaps.  Good (logarithmic) performance with random data  Linear performance if the data is sorted ◦ Solutions – Splay Trees Amortized O( lg n) performance.
Trees Types and Operations
IKI 10100: Data Structures & Algorithms Ruli Manurung (acknowledgments to Denny & Ade Azurat) 1 Fasilkom UI Ruli Manurung (Fasilkom UI)IKI10100: Lecture20.
IKI 10100I: Data Structures & Algorithms Ruli Manurung (acknowledgments to Denny & Ade Azurat) 1 Fasilkom UI Ruli Manurung (Fasilkom UI)IKI10100I: Data.
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.
© 2006 Pearson Addison-Wesley. All rights reserved11 B-1 Chapter 11 (continued) Trees.
Chapter 9 contd. Binary Search Trees Anshuman Razdan Div of Computing Studies
Tree Traversals A traversal is a way of walking the tree structure Some common traversals: –pre-order traversal –in-order traversal –post-order traversal.
1 Section 9.2 Tree Applications. 2 Binary Search Trees Goal is implementation of an efficient searching algorithm Binary Search Tree: –binary tree in.
Binary Trees Like a list, a (binary) tree can be empty or non-empty. In class we will explore a state-based implementation, similar to the LRStruct You.
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.
1 Joe Meehean.  Important and common problem  Given a collection, determine whether value v is a member  Common variation given a collection of unique.
Binary Search Trees. BST Properties Have all properties of binary tree Items in left subtree are smaller than items in any node Items in right subtree.
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.
CSCE 3110 Data Structures & Algorithm Analysis Binary Search Trees Reading: Chap. 4 (4.3) Weiss.
B-trees (Balanced Trees) A B-tree is a special kind of tree, similar to a binary tree. However, It is not a binary search tree. It is not a binary tree.
Sorted Array What is BigO for sorted list implemented as: ArrayList: – Search : – Insert(value) : – Remove(value) : LinkedList: – Search : – Insert(value)
© 2011 Pearson Addison-Wesley. All rights reserved 11 B-1 Chapter 11 (continued) Trees.
CISC220 Fall 2009 James Atlas Lecture 13: Trees. Skip Lists.
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 Search Trees Binary Search Trees (BST)  the tree from the previous slide is a special kind of binary tree called a binary.
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.
CS 361 – Chapter 3 Sorted dictionary ADT Implementation –Sorted array –Binary search tree.
Chapter 11 B Trees. © 2004 Pearson Addison-Wesley. All rights reserved 11 B-2 The ADT Binary Search Tree A deficiency of the ADT binary tree which is.
Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Modified for use at Midwestern State University Chapter.
Topics Definition and Application of Binary Trees Binary Search Tree Operations.
Chapter 19: Binary Search Trees or How I Learned to Love AVL Trees and Balance The Tree Group 6: Tim Munn.
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.
1/14/20161 BST Operations Data Structures Ananda Gunawardena.
Trees 3 The Binary Search Tree Section 4.3. Binary Search Tree Also known as Totally Ordered Tree Definition: A binary tree B is called a binary search.
1 Binary Trees and Binary Search Trees Based on Dale & Co: Object-Oriented Data Structures using C++ (graphics)
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.
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.
(c) University of Washington20c-1 CSC 143 Binary Search Trees.
A Binary Search Tree Implementation Chapter 25 © 2015 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures and Abstractions.
TCSS 342, Winter 2006 Lecture Notes
CSCE 3110 Data Structures & Algorithm Analysis
CSCE 3110 Data Structures & Algorithm Analysis
Trees Chapter 11 (continued)
CSE 373 Binary search trees; tree height and balance
Binary Trees and Binary Search Trees
Trees Chapter 11 (continued)
BST Trees
Binary search tree. Removing a node
CISC220 Fall 2009 James Atlas Lecture 13: Binary Trees.
Week 6 - Wednesday CS221.
Binary Search Tree (BST)
Lecture 22 Binary Search Trees Chapter 10 of textbook
Trees.
COMP 103 Binary Search Trees.
Binary Search Trees.
Chapter 22 : Binary Trees, AVL Trees, and Priority Queues
Binary Search Trees.
Find in a linked list? first last 7  4  3  8 NULL
A Robust Data Structure
Binary Search Trees.
Ch. 12 Tables and Priority Queues
Binary Search Trees Chapter 9 2/22/2019 B.Ramamurthy.
Binary Search Trees Chapter 9 2/24/2019 B.Ramamurthy.
CSC 143 Java Trees.
CSC 143 Binary Search Trees.
Yan Shi CS/SE 2630 Lecture Notes
Trees.
Trees Trees.
Chapter 11 Trees © 2011 Pearson Addison-Wesley. All rights reserved.
NATURE VIEW OF A TREE leaves branches root. NATURE VIEW OF A TREE leaves branches root.
Presentation transcript:

Binary Trees Like a list, a (binary) tree can be empty or non-empty. In class we will explore a state-based implementation, similar to the LRS You are expected to read about alternate implementation strategies in the textbook

Method of a Binary Recursive Structure (BRS) method to grow tree: insertRoot method to shrink tree: removeRoot accessor/mutator pair for root: setRoot/getRoot accessor/mutator pair for left: setLeft/getLeft accessor/mutator pair for right: setRight/getRight visitor support: execute

State transitions Empty  NonEmpty: insertRoot on an empty tree NonEmpty  Empty: removeRoot from a tree that is a leaf –A leaf is a tree both of whose children are empty. No other state transitions can occur.

Moreover… insertRoot throws an exception if called on a nonEmpty tree removeRoot throws an exception if called on a non-leaf tree Isn’t this very restrictive?

Yes…but It is very restrictive, but for good reasons: –What would it mean to add a root to a tree that already has one? –If you could remove the root from a tree with nonEmpty children, what would become of those children?

Usage of a BRS A BRS is not used “raw”, but is used to implement more specialized trees. Consider how we defined the SortedList in terms of the LRS: by composition. We will now explore how to define a sorted binary tree (a Binary Search Tree) by composition with a BRS.

Binary Search Tree (BST) A binary search tree (BST) is a binary tree which maintains its elements in order. The BST order condition requires that, for every non-empty tree, the value at the root is greater than every value in the tree’s left subtree, and less than every value in the tree’s right subtree.

Example 1 Does this tree satisfy the BST order condition? Fred WilmaBetty BarneyPebbles

No! Barney Fred < Wilma Fred WilmaBetty BarneyPebbles

Example 2 Does this tree satisfy the BST order condition? Fred WilmaBetty BarneyPebbles

Yes! Barney < Betty < Fred < Pebbles < Wilma Fred WilmaBetty BarneyPebbles

Example 3 Does this tree satisfy the BST order condition? Fred WilmaBetty BarneyPebbles

No! Betty > Barney < Fred < Pebbles < Wilma Fred WilmaBetty BarneyPebbles

Example 4 …but if we swap Betty & Barney, we restore order! Fred Wilma Betty Barney Pebbles

Operations on a BST public BST insert(Comparable item) public BST remove(Comparable item) public boolean member(Comparable item) How do we support these? They don’t exist as methods on the BRS.

Visitors to the rescue! Visitors on the BRS have the same basic structure as on the LRS: they deal with two cases: –public Object emptyCase(BRS host, Object inp) –public Object nonEmptyCase(BRS host, Object inp)

Example: toStringVisitor public class ToStringVisitor extends IAlgo { public static final ToStringVisitor SINGLETON = new ToStringVisitor(); private ToStringVisitor() {} public Object emptyCase(BRS host, Object input) { return "[]"; } public Object nonEmptyCase(BRS host, Object input) { return "[" + host.getLeft().execute(this, null) + " " + host.getRoot().toString() + " " + host.getRight().execute(this, null) + "]"; }

Back to the BST Let’s first consider the insert operation. We must consider two possibilities: –the underlying BRS is empty just insertRoot –the underlying BRS is nonEmpty we can’t insertRoot, because the BRS is nonEmpty compare new item with root – determine whether new item belongs in left or right subtree – insert recursively into correct subtree

A first cut at the visitor public class InsertVisitor extends IAlgo { public Object emptyCase(BRS host, Object item) { return host.insertRoot(item); } public Object nonEmptyCase(BRS host, Object item) { if ( ((Comparable) item).compareTo(host.getRoot()) < 0 ) { // item belongs in left subtree return host.getLeft().execute(this, item); } else if ( ((Comparable) item).compareTo(host.getRoot()) > 0 ) { // item belongs in right subtree return host.getRight().execute(this, item); } else {// item is already in tree (Note UNIQUENESS ASSUMPTION) return host; }

How about determining membership for an item? We must consider two possibilities: –the underlying BRS is empty just item was not found –the underlying BRS is nonEmpty compare new item with root – determine whether new item has been found, or whether it would be in left or right subtree – look recursively into correct subtree

A first cut at the visitor public class MemberVisitor extends IAlgo { public Object emptyCase(BRS host, Object item) { return new Boolean(false); } public Object nonEmptyCase(BRS host, Object item) { if ( ((Comparable) item).compareTo(host.getRoot()) < 0 ) { // item belongs in left subtree return host.getLeft().execute(this, item); } else if ( ((Comparable) item).compareTo(host.getRoot()) > 0 ) { // item belongs in right subtree return host.getRight().execute(this, item); } else {// item is already in tree (Note UNIQUENESS ASSUMPTION) return new Boolean(true); }

Did you notice similarity? The structure of the insert and membership visitors was the same. A small number of details differed. Let’s unify!

The find visitor public class Find extends IAlgo { public Object emptyCase(BRS host, Object item) { return host; } public Object nonEmptyCase(BRS host, Object item) { if ( ((Comparable) item).compareTo(host.getRoot()) < 0 ) { // item belongs in left subtree return host.getLeft().execute(this, item); } else if ( ((Comparable) item).compareTo(host.getRoot()) > 0 ) { // item belongs in right subtree return host.getRight().execute(this, item); } else {// item is already in tree (Note UNIQUENESS ASSUMPTION) return host; }

Look at BST implementation insert, remove and member ALL make use of the same Find visitor: –first find the insertionPoint, –then do the right thing.

The insert method public BST insert(Comparable item) { BRS insertPoint = (BRS) _tree.execute(new Find(), item); only insert item into insertPoint if empty (duplicates ignored) return this; }

The insert method public BST insert(Comparable item) { BRS insertPoint = (BRS) _tree.execute(new Find(), item); insertPoint.execute(new IAlgo() { public Object emptyCase(BRS host, Object input) { host.insertRoot(input); return null; } public Object nonEmptyCase(BRS host, Object input) { return null; } }, item); return this; }

The member method public boolean member(Comparable item) { BRS insertPoint = (BRS) _tree.execute(new Find(), item); return whether insertPoint is empty or nonEmpty }

The member method public boolean member(Comparable item) { BRS insertPoint = (BRS) _tree.execute(new Find(), item); return ((Boolean) insertPoint.execute(new IAlgo() { public Object emptyCase(BRS host, Object input) { return new Boolean(false); } public Object nonEmptyCase(BRS host, Object input) { return new Boolean(true); } }, null)).booleanValue(); }

The remove method public BST remove(final Comparable item) { BRS removePoint = (BRS) _tree.execute(new Find(), item); handle removal differently in five different cases: empty tree non-empty tree with both children empty (leaf case) non-empty tree with left child empty, right child non-empty non-empty tree with left child non-empty, right child empty non-empty tree with both children non-empty return this; }

The remove method public BST remove(final Comparable item) { BRS removePoint = (BRS) _tree.execute(new Find(), item); removePoint.execute(new FiveStateVisitor() { private IAlgo theRemovalVisitor = this; public Object emptyCase(BRS host, Object input) { return host; } public Object leafCase(BRS host, Object input) { host.removeRoot(); return host; } public Object leftNonEmptyCase(BRS host, Object input) { host.setRoot(host.getLeft().getRoot()); host.setRight(host.getLeft().getRight()); host.setLeft(host.getLeft().getLeft()); return host; } public Object rightNonEmptyCase(BRS host, Object input) { host.setRoot(host.getRight().getRoot()); host.setLeft(host.getRight().getLeft()); host.setRight(host.getRight().getRight()); return host; } public Object leftRightNonEmptyCase(BRS host, Object input) { Object smallestInRight = host.getRight().execute(new IAlgo() { public Object emptyCase(BRS host, Object parent) { Object smallest = ((BRS) parent).getRoot(); ((BRS) parent).execute(theRemovalVisitor, null); return smallest; } public Object nonEmptyCase(BRS host, Object parent) { return host.getLeft().execute(this, host); } }, null); host.setRoot(smallestInRight); return host; } }, item); return this; }

Question How do we make the 5-way distinction? See the FiveStateVisitor definition in the lecture code repository. Basic idea: check left, then check right.