Tree Implementations (plus briefing about Iterators)

Slides:



Advertisements
Similar presentations
A Binary Search Tree Implementation Chapter Chapter Contents Getting Started An Interface for the Binary Search Tree Duplicate Entries Beginning.
Advertisements

© 2006 Pearson Addison-Wesley. All rights reserved11 B-1 Chapter 11 (continued) Trees.
Trees Chapter Chapter Contents Tree Concepts Hierarchical Organizations Tree Terminology Traversals of a Tree Traversals of a Binary Tree Traversals.
Fall 2007CS 2251 Iterators and Tree Traversals. Fall 2007CS 2252 Binary Trees In a binary tree, each node has at most two subtrees A set of nodes T is.
Iterators Chapter 7. Chapter Contents What is an Iterator? A Basic Iterator Visits every item in a collection Knows if it has visited all items Doesn’t.
Razdan CST230http://dcst2.east.asu.edu/~razdan/cst230/ Razdan with contribution from others 1 Chapter 9 Trees Anshuman Razdan Div of Computing Studies.
A Binary Search Tree Implementation Chapter Chapter Contents Getting Started An Interface for the Binary Search Tree Duplicate Entries Beginning.
Tree Implementations Chapter Nodes in a Binary Tree The most common way uses a linked structure with each node represent each element in a binary.
Trees Chapter 23 Copyright ©2012 by Pearson Education, Inc. All rights reserved.
Trees. 2 Tree Concepts Previous data organizations place data in linear order Some data organizations require categorizing data into groups, subgroups.
A Binary Search Tree Implementation Chapter 25 Copyright ©2012 by Pearson Education, Inc. All rights reserved.
Tree Implementations Chapter 24 Copyright ©2012 by Pearson Education, Inc. All rights reserved.
04 Trees Part I CS 310 photo ©Oregon Scenics used with permissionOregon Scenics All figures labeled with “Figure X.Y” Copyright © 2006 Pearson Addison-Wesley.
Marc Smith and Jim Ten Eyck
A Binary Search Tree Implementation Chapter 27 Slides by Steve Armstrong LeTourneau University Longview, TX  2007,  Prentice Hall.
Chapter 18 - basic definitions - binary trees - tree traversals Intro. to Trees 1CSCI 3333 Data Structures.
Trees & Graphs Chapter 25 Carrano, Data Structures and Abstractions with Java, Second Edition, (c) 2007 Pearson Education, Inc. All rights reserved X.
Lecture Objectives  To learn how to use a tree to represent a hierarchical organization of information  To learn how to use recursion to process trees.
© 2011 Pearson Addison-Wesley. All rights reserved 11 B-1 Chapter 11 (continued) Trees.
Topic 14 The BinaryTree ADT Objectives Define trees as data structures Define the terms associated with trees Discuss tree traversal algorithms.
IKI 10100I: Data Structures & Algorithms Ruli Manurung (acknowledgments to Denny & Ade Azurat) 1 Fasilkom UI Ruli Manurung (Fasilkom UI)IKI10100I: Data.
Trees Chapter Chapter Contents Tree Concepts Hierarchical Organizations Tree Terminology Traversals of a Tree Traversals of a Binary Tree Traversals.
1 CMPSCI 187 Computer Science 187 Introduction to Introduction to Programming with Data Structures Lecture 16: Trees Announcements 1.Programming project.
Iterators (short version) Chapter 15 Copyright ©2012 by Pearson Education, Inc. All rights reserved.
Tree Implementations Chapter 24 © 2015 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures and Abstractions with Java,
Tree Implementations Chapter Chapter Contents The Nodes in a Binary Tree An Interface for a Node An implementation of BinaryNode An Implementation.
COSC2007 Data Structures II Chapter 11 Trees II. 2 Topics ADT Binary Tree (BT) Operations Tree traversal BT Implementation Array-based LL-based Expression.
CMSC 341 Binary Search Trees. 8/3/2007 UMBC CMSC 341 BST 2 Binary Search Tree A Binary Search Tree is a Binary Tree in which, at every node v, the values.
CSC 205 Java Programming II Lecture 26 Traversing Binary Tree.
Topic 13 Iterators. 9-2 Motivation We often want to access every item in a data structure or collection in turn We call this traversing or iterating over.
Iterator Summary Slides by Entesar Al-Mosallam adopted from Steve Armstrong LeTourneau University Longview, TX  2007,  Prentice Hall.
IKI 10100: Data Structures & Algorithms Ruli Manurung (acknowledgments to Denny & Ade Azurat) 1 Fasilkom UI Ruli Manurung (Fasilkom UI)IKI10100: Lecture13.
Iterators. Iterator  An iterator is any object that allows one to step through each element in a list (or, more generally, some collection).
Iterators.
The Tree ADT.
Podcast Ch17b Title: Iterative Tree Traversal
Trees Chapter 11 (continued)
Basic Tree Data Structures
Trees Chapter 11 (continued)
A Binary Search Tree Implementation
Chapter 11 Trees © 2011 Pearson Addison-Wesley. All rights reserved.
COMP 103 Binary Search Trees.
A Binary Search Tree Implementation
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.
A Bag Implementation that Links Data
Copyright ©2012 by Pearson Education, Inc. All rights reserved
Copyright ©2012 by Pearson Education, Inc. All rights reserved
CMSC 341 Binary Search Trees 11/19/2018.
Trees.
Iterators (short version)
Copyright ©2012 by Pearson Education, Inc. All rights reserved
Slides by Steve Armstrong LeTourneau University Longview, TX
CMSC 341 Binary Search Trees.
Iterators (partial) Chapter 8 Slides by Nadia Al-Ghreimil
CMSC 341 Binary Search Trees 1/3/2019.
General Trees & Binary Trees
Copyright ©2012 by Pearson Education, Inc. All rights reserved
CMSC 341 Binary Search Trees 2/23/2019.
A Heap Implementation Chapter 26 Adapted from Pearson Education, Inc.
CMSC 341 Binary Search Trees.
Podcast Ch18d Title: Binary Search Tree Iterator
Chapter 11 Trees © 2011 Pearson Addison-Wesley. All rights reserved.
CMSC 341 Binary Search Trees 5/8/2019.
CMSC 341 Binary Search Trees 5/28/2019.
CMSC 341 Binary Search Trees 8/3/2007 CMSC 341 BST.
These notes are intended for use by students in CS0445 at the University of Pittsburgh and no one else These notes are provided free of charge and may.
CMSC 341 Binary Search Trees 2/21/2006.
A Binary Search Tree Implementation
Binary Tree Iterators Tree Traversals: preorder, inorder, postorder
Presentation transcript:

Tree Implementations (plus briefing about Iterators) Chapter 24 Adapted from Pearson Education, Inc.

Contents The Nodes in a Binary Tree An Interface for a Node An Implementation of BinaryNode An Implementation of the ADT Binary Tree Creating a Basic Binary Tree The Method privateSetTree Computing the Height and Counting Nodes Traversals & Iterators An Implementation of an Expression Tree General Trees A Node for a General Tree Using a Binary Tree to Represent a General Tree Adapted from Pearson Education, Inc.

Objectives Describe necessary operations on node within binary tree Implement class of nodes for binary tree Implement class of binary trees Implement an expression tree by extending class of binary trees Describe necessary operations on a node within general tree Use binary tree to represent general tree Adapted from Pearson Education, Inc.

Interfaces…(review from ch 23) package TreePackage; public interface TreeInterface < T > { public T getRootData (); public int getHeight (); public int getNumberOfNodes (); public boolean isEmpty (); public void clear (); } // end TreeInterface package TreePackage; import java.util.Iterator; public interface TreeIteratorInterface < T > { public Iterator < T > getPreorderIterator (); public Iterator < T > getPostorderIterator (); public Iterator < T > getInorderIterator (); public Iterator < T > getLevelOrderIterator (); } // end TreeIteratorInterface package TreePackage; public interface BinaryTreeInterface < T > extends TreeInterface < T > , TreeIteratorInterface < T > { public void setTree (T rootData); public void setTree (T rootData, BinaryTreeInterface < T > leftTree, BinaryTreeInterface < T > rightTree); } // end BinaryTreeInterface Adapted from Pearson Education, Inc.

An Interface for a Node An implementation of BinaryNode, Listing 24-2 package TreePackage; interface BinaryNodeInterface < T > { public T getData (); public void setData (T newData); public BinaryNodeInterface < T > getLeftChild (); public BinaryNodeInterface < T > getRightChild (); public void setLeftChild (BinaryNodeInterface < T > leftChild); public void setRightChild (BinaryNodeInterface < T > rightChild); public boolean hasLeftChild (); public boolean hasRightChild (); public boolean isLeaf (); /** Counts the nodes in the subtree rooted at this node. @return the number of nodes in the subtree rooted at this node */ public int getNumberOfNodes (); /** Computes the height of the subtree rooted at this node. @return the height of the subtree rooted at this node */ public int getHeight (); public BinaryNodeInterface < T > copy (); } // end BinaryNodeInterface An implementation of BinaryNode, Listing 24-2 Adapted from Pearson Education, Inc.

Implementation of a basic Binary Tree First draft of the class, Listing 24-3 Notice private method privateSetTree: private void privateSetTree (T rootData, BinaryTree < T > leftTree, BinaryTree < T > rightTree) { /* FIRST DRAFT - See Segments 24.5 - 24.8 for improvements. */ root = new BinaryNode < T > (rootData) ; if (leftTree != null) root.setLeftChild (leftTree.root); if (rightTree != null) root.setRightChild (rightTree.root); } // end privateSetTree Result of calling: treeA.setTree(a, treeB, treeC) Adapted from Pearson Education, Inc.

Problems with PrivateSetTree Result of calling: treeA.setTree(a, treeB, treeB) Can be solved as follows: private void privateSetTree (T rootData, BinaryTree < T > leftTree, BinaryTree < T > rightTree) { root = new BinaryNode < T > (rootData); if ((leftTree != null) && !leftTree.isEmpty ()) root.setLeftChild (leftTree.root.copy ()); if ((rightTree != null) && !rightTree.isEmpty ()) root.setRightChild (rightTree.root.copy ()); } // end privateSetTree But copy is expensive: public BinaryNodeInterface < T > copy () { BinaryNode < T > newRoot = new BinaryNode < T > (data); if (left != null) newRoot.left = (BinaryNode<T>) left.copy (); if (right!= null) newRoot.right =(BinaryNode<T>) right.copy (); return newRoot; } // end copy So what is the solution? Adapted from Pearson Education, Inc.

Recursive In-Order traversal of a BT Public method for user, calls private method Adapted from Pearson Education, Inc.

Iterators vs regular traversal What if I want to do something at each node? I need to be able to stop at each node I need to be able to control when to go to the next node Iterators have these methods: (see ch. 15) public boolean hasNext (); public T next (); public void remove (); // Optional method Iterators allow you to step through a structure, one step at a time. See complete interface Iterator, Listing 15-1 Adapted from Pearson Education, Inc.

Adapted from Pearson Education, Inc. Using iterators (ch 15) ListWithIteratorInterface <String> nameList = new ArrayListWithIterator <String>(); nameList.add(“Maha”); nameList.add(“Nadia”); nameList.add(“Rehab”); Iterator < String > nameIterator = nameList.getIterator(); nameIterator.remove(); if(nameIterator.hasNext()) nameIterator.next(); System.out.println (nameIterator.next()); nameList nameIterator Maha Nadia Rehab IllegalStateException Print “Nadia” As we go through this example, ask the students to look at the interface for iterators. Q - At the first remove, ask students they can predict what will happen. A - exception Q - Then ask them why it happened A - we did not call next() yet. At the second remove statement, point out that a call to next should give us “Rehab”, we have to make sure in our implementation that that will be the case. Ask the students where they think the arrow will be after removal? Only then click for next slide!! Adapted from Pearson Education, Inc.

Adapted from Pearson Education, Inc. Using iterators (ch 15) ListWithIteratorInterface <String> nameList = new LinkedListWithIterator <String>(); nameList.add(“Maha”); nameList.add(“Nadia”); nameList.add(“Rehab”); Iterator < String > nameIterator = nameList.getIterator(); if(nameIterator.hasNext()) nameIterator.next(); System.out.println (nameIterator.next()); nameIterator.remove(); nameList nameIterator Maha Rehab Adapted from Pearson Education, Inc.

Iterative In-Order Traversal of a BT public void inorderTraverse () { StackInterface <BinaryNodeInterface<T>> nodeStack = new LinkedStack <BinaryNodeInterface<T>> (); BinaryNodeInterface < T > currentNode = root; while (!nodeStack.isEmpty () || (currentNode != null)) { // find leftmost node with no left child while (currentNode != null) { nodeStack.push (currentNode); currentNode = currentNode.getLeftChild (); } // end while // visit leftmost node, then traverse its right subtree if (!nodeStack.isEmpty ()) { BinaryNodeInterface < T > nextNode = nodeStack.pop (); System.out.println (nextNode.getData ()); currentNode = nextNode.getRightChild (); } // end if } // end inorderTraverse Adapted from Pearson Education, Inc.

In-Order Traversal with an Iterator private class InorderIterator implements Iterator < T > { private StackInterface < BinaryNodeInterface < T >> nodeStack; private BinaryNodeInterface < T > currentNode; public InorderIterator () nodeStack = new LinkedStack < BinaryNodeInterface < T >> (); currentNode = root; } // end default constructor public boolean hasNext () return ( !nodeStack.isEmpty () || (currentNode != null) ); } // end hasNext Adapted from Pearson Education, Inc.

In-Order Traversal with an Iterator public T next () { BinaryNodeInterface < T > nextNode = null; // find leftmost node with no left child while (currentNode != null) { nodeStack.push (currentNode); currentNode = currentNode.getLeftChild (); } // end while // get leftmost node, then move to its right subtree if (!nodeStack.isEmpty ()) { nextNode = nodeStack.pop (); currentNode = nextNode.getRightChild (); } else throw new NoSuchElementException (); return nextNode.getData (); } // end next public void remove () { throw new UnsupportedOperationException (); } // end remove } // end InorderIterator Adapted from Pearson Education, Inc.

Tracing of inorderTraverse() Adapted from Pearson Education, Inc.

Using a stack to do a pre-order traversal Adapted from Pearson Education, Inc.

Using a stack to do a post-order traversal Adapted from Pearson Education, Inc.

Using a queue to do a level-order traversal c d X c d e c Adapted from Pearson Education, Inc.

Implementation of an Expression Tree Note interface, Listing 24-5 Derive from BinaryTree, Listing 24-6 Adapted from Pearson Education, Inc.

Figure 24-8 A node for a general tree Adapted from Pearson Education, Inc.

Node for a General Tree Interface, Listing 24-7 Adapted from Pearson Education, Inc.

Using a Binary Tree to Represent a General Tree Figure 24-9 (a) A general tree; (b) an equivalent binary tree; Adapted from Pearson Education, Inc.

End Chapter 24 Adapted from Pearson Education, Inc.