COSC2007 Data Structures II Chapter 10 Trees II. 2 Topics ADT Binary Tree (BT) Operations Tree traversal BT Implementation Array-based LL-based Expression.

Slides:



Advertisements
Similar presentations
Numbers Treasure Hunt Following each question, click on the answer. If correct, the next page will load with a graphic first – these can be used to check.
Advertisements

Chapter 25 Lists, Stacks, Queues, and Priority Queues
TK1924 Program Design & Problem Solving Session 2011/2012
CS Data Structures I Chapter 6 Stacks I 2 Topics ADT Stack Stack Operations Using ADT Stack Line editor Bracket checking Special-Palindromes Implementation.
1
Chapter 17 Linked Data Structures. Copyright © 2006 Pearson Addison-Wesley. All rights reserved Learning Objectives Nodes and Linked Lists Creating,
Copyright © 2003 Pearson Education, Inc. Slide 1 Computer Systems Organization & Architecture Chapters 8-12 John D. Carpinelli.
Copyright © 2011, Elsevier Inc. All rights reserved. Chapter 6 Author: Julia Richards and R. Scott Hawley.
Properties Use, share, or modify this drill on mathematic properties. There is too much material for a single class, so you’ll have to select for your.
Custom Statutory Programs Chapter 3. Customary Statutory Programs and Titles 3-2 Objectives Add Local Statutory Programs Create Customer Application For.
Chapter 7. Binary Search Trees
1 Click here to End Presentation Software: Installation and Updates Internet Download CD release NACIS Updates.
Break Time Remaining 10:00.
Turing Machines.
Table 12.1: Cash Flows to a Cash and Carry Trading Strategy.
PP Test Review Sections 6-1 to 6-6
Chapter 17 Linked Lists.
Chapter 4 Linked Lists. © 2005 Pearson Addison-Wesley. All rights reserved4-2 Preliminaries Options for implementing an ADT List –Array has a fixed size.
DATA STRUCTURES AND ALGORITHMS Prepared by İnanç TAHRALI
Linked Lists Chapter 4.
Chapter 24 Lists, Stacks, and Queues
11 Data Structures Foundations of Computer Science ã Cengage Learning.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver Chapter 4: Linked Lists Data Abstraction & Problem Solving with.
Abstract Data Types and Algorithms
Data Structures Part 2 Stacks, Queues, Trees, and Graphs Briana B. Morrison CSE 1302C Spring 2010.
Double-Linked Lists and Circular Lists
Chapter 1 Object Oriented Programming 1. OOP revolves around the concept of an objects. Objects are created using the class definition. Programming techniques.
1 Linked Lists A linked list is a sequence in which there is a defined order as with any sequence but unlike array and Vector there is no property of.
Bright Futures Guidelines Priorities and Screening Tables
Searching: Binary Trees and Hash Tables
Bellwork Do the following problem on a ½ sheet of paper and turn in.
Exarte Bezoek aan de Mediacampus Bachelor in de grafische en digitale media April 2014.
1 public class Newton { public static double sqrt(double c) { double epsilon = 1E-15; if (c < 0) return Double.NaN; double t = c; while (Math.abs(t - c/t)
Copyright © 2012, Elsevier Inc. All rights Reserved. 1 Chapter 7 Modeling Structure with Blocks.
1 RA III - Regional Training Seminar on CLIMAT&CLIMAT TEMP Reporting Buenos Aires, Argentina, 25 – 27 October 2006 Status of observing programmes in RA.
Basel-ICU-Journal Challenge18/20/ Basel-ICU-Journal Challenge8/20/2014.
Adding Up In Chunks.
Copyright © 2013 by John Wiley & Sons. All rights reserved. HOW TO CREATE LINKED LISTS FROM SCRATCH CHAPTER Slides by Rick Giles 16 Only Linked List Part.
1 10 pt 15 pt 20 pt 25 pt 5 pt 10 pt 15 pt 20 pt 25 pt 5 pt 10 pt 15 pt 20 pt 25 pt 5 pt 10 pt 15 pt 20 pt 25 pt 5 pt 10 pt 15 pt 20 pt 25 pt 5 pt Synthetic.
© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of CHAPTER 11: Priority Queues and Heaps Java Software Structures: Designing.
1 hi at no doifpi me be go we of at be do go hi if me no of pi we Inorder Traversal Inorder traversal. n Visit the left subtree. n Visit the node. n Visit.
1 Let’s Recapitulate. 2 Regular Languages DFAs NFAs Regular Expressions Regular Grammars.
Essential Cell Biology
Clock will move after 1 minute
PSSA Preparation.
Essential Cell Biology
Immunobiology: The Immune System in Health & Disease Sixth Edition
Physics for Scientists & Engineers, 3rd Edition
Energy Generation in Mitochondria and Chlorplasts
1 Decidability continued…. 2 Theorem: For a recursively enumerable language it is undecidable to determine whether is finite Proof: We will reduce the.
CSCE 2100: Computing Foundations 1 The Tree Data Model
CSC 205 – Java Programming II Lecture 35 April 17, 2002.
© 2006 Pearson Addison-Wesley. All rights reserved11 A-1 Chapter 11 Trees.
Marc Smith and Jim Ten Eyck
Chapter 11 A Trees. © 2004 Pearson Addison-Wesley. All rights reserved 11 A-2 Terminology A tree consists of vertices and edges, –An edge connects to.
1 TK1924 Program Design & Problem Solving Session 2011/2012 L8: Binary Trees.
Course: Programming II - Abstract Data Types Slide Number 1 The ADT Binary Tree Definition The ADT Binary Tree is a finite set of nodes which is either.
Binary Trees 2 Overview Trees. Terminology. Traversal of Binary Trees. Expression Trees. Binary Search Trees.
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.
COSC2007 Data Structures II Chapter 11 Trees IV. 2 Topics ADT BST Implementations Efficiency TreeSort Save/Restore into/from file General Trees.
© 2006 Pearson Addison-Wesley. All rights reserved11 A-1 Chapter 11 Trees.
COSC2007 Data Structures II Chapter 11 Trees II. 2 Topics ADT Binary Tree (BT) Operations Tree traversal BT Implementation Array-based LL-based Expression.
CSC 205 Java Programming II Lecture 26 Traversing Binary Tree.
Chapter 11 Trees © 2011 Pearson Addison-Wesley. All rights reserved.
Csc 2720 Instructor: Zhuojun Duan
Chapter 11 Trees © 2011 Pearson Addison-Wesley. All rights reserved.
Binary Tree Traversal Methods
CSC 205 – Java Programming II
Presentation transcript:

COSC2007 Data Structures II Chapter 10 Trees II

2 Topics ADT Binary Tree (BT) Operations Tree traversal BT Implementation Array-based LL-based Expression Notation and Tree traversal

3 ADT Binary Tree

4 Operations +CreateBinaryTree() // Creates an empty Binary Tree +CretaeBinaryTree(in rootItem:TreeItemType) // Creates a one-node BT whose root contains RootItem +CreateBT(in rootItem:TreeItemType,inout leftTree:BinaryTree,inout rightTree:BinaryTree) // Creates a BT with root data RootItem and a leftTree and rightTree, // respectively as its left & right subtrees. Makes leftTree & rightTree empty // so they cant be used to gain access to the new tree. +destroyBinaryTree() // Destroys a binary tree +isEmpty():boolean {query} // Determines whether a binary tree is empty root:

5 ADT Binary Tree Operations +getRootData():TreeItemType throw TreeException // Returns the data item in the root of a nonempty subtree. // Throws an exception if the tree is empty +setRootData(in newItem:TreeItemType) throw TreeException // Replaces the data item in the root of a binary tree with newItem, if the // tree is not empty, otherwise a root node is created with newItem as its data // item and is inserted in the tree. // If a new node cant be created, TreeException is thrown +attachLeft(in newItem: TreeItemType) throw TreeException // Attaches a left child containing newItem to the root of a binary tree. // Throws TreeException if the operation the binary tree is empty // or a left subtree already exists. +attachRight(in newItem:TreeItemType) throw TreeException // Attaches a left child containing newItem to the root of a binary tree. // Throws TreeException if the operation the binary tree is empty // or a right subtree already exists. root: tree1: root: tree1:

6 ADT Binary Tree Operations +attachLeftSubtree(inout leftTree:BinaryTree) throw TreeException // Attaches leftTree as the left subtree of the root of a binary tree and makes // leftTree empty so that it cant be used to access this tree. Throws // TreeException is the binary tree is empty or a left subtree already exists. +attachRightSubtree(inout rightTree:BinaryTree) throw TreeException // Attaches rightTree as the right subtree of the root of a binary tree and makes // rightTree empty so that it cant be used to access this tree. Throws // TreeException is the binary tree is empty or a right subtree already exists. +detachLeftSubtree(out leftTree:BinaryTree) ThrowTreeException // Detaches the left subtree of a binary trees root. and retains it in // leftTree. Throws TreeException if the tree is empty. +detachRightSubtree(out rightTree:BinaryTree) ThrowTreeException // Detaches the right subtree of a binary trees root. and retains it in // rightTree. Throws TreeException if the tree is empty.

7 ADT Binary Tree Operations +leftSubtree( ):BinaryTree // Returns a copy of the left subtree of a binary trees root without // detaching the subtree. Returns an empty tree if the binary tree is empty. +rightSubtree( ):BinaryTree // Returns a copy of the right subtree of a binary trees root without // detaching the subtree. Returns an empty tree if the binary tree is empty. +preorderTraverse(in visit:FunctionType) // Traverses a binary tree in preorder & // calls function visit() once for each node +inorderTraverse(in visit:FunctionType) // Traverses a binary tree in inorder & // calls function visit() once for each node +postorderTraverse(in visit:FunctionType) // Traverses a binary tree in postorder & // calls function visit() once for each node

8 BT Traversal Suppose I wanted to visit all the nodes in this tree. Furthermore, suppose I wanted to perform some operation on the data there (such as printing it out). A B DE H IJK C FG L root What are some of the possible visitation patterns we could use?

9 BT Traversal Visit every node in a BT exactly once. Each visit performs the same operations on each node Visiting sequence of nodes is of importance Natural traversal orders: Pre-order Depth-First or Node-Left-Right (NLR) In-order Symmetric or Left-Node-Right (LNR) Post-order Left-Right-Node (LRN)

10 Pre-order Traversal Each node is processed the first time it is observed. i.e. before any node in either subtree. A Possible Pattern Visit Root Node Visit Left subtree in preorder Visit Right subtree Must be applied at all levels of the tree. A B DE H IJK C FG L root Called an PreOrder Traversal A B D H I E J K C F G L

11 Pre-order Traversal Pseudocode preorder (binaryTree:BinaryTree ) // Traverses the binary tree binaryTree in preorder. // Assumes that visit a node means to display the nodes data item if (binaryTree is not empty ) { Display the data in the root of binaryTree preorder ( Left subtree of binaryTree s root ) preorder ( Right subtree of binaryTree s root ) }

12 In-order Traversal Each node is processed the second time it is observed. i.e. after all the nodes in its left subtree but before any of the nodes in its right subtree. A Possible Pattern Visit Left subtree Visit Root node Visit Right subtree Must be applied at all levels of the tree. A B DE H IJK C FG L root H D I B J E K A F C G L

13 In-order Traversal Pseudocode inorder (binaryTree:BinaryTree ) // Traverses the binary tree binaryTree in inorder. // Assumes that visit a node means to display the nodes data item if (binaryTree is not empty ) { inorder ( Left subtree of binaryTree s root ) Display the data in the root of binaryTree inorder ( Right subtree of binaryTree s root ) }

14 Post-order Traversal Each node is processed the third time it is observed. i.e. after all nodes in both of its subtrees. A Possible Pattern Visit Left subtree Visit Right subtree Visit Root Node Must be applied at all levels of the tree. A B DE H IJK C FG L root H I D J K E B F L G C A

15 Post-order Traversal Pseudocode postorder (binaryTree:BinaryTree ) // Traverses the binary tree binaryTree in postorder. // Assumes that visit a node means to display the nodes data item if (binaryTree is not empty ) { postorder ( Left subtree of binaryTree s root ) postorder ( Right subtree of binaryTree s root ) Display the data in the root of binaryTree }

16 Implementation of BT Possible Implementations: Array based Fast access Difficult to change Used if elements are not modified often Reference (Pointer) based Slower Easy to modify More flexible when elements are modified often

17 BT Array-Based Implementation Nodes: A Java Node class Each node should contain: Data portion Left-child index Right-child index Tree: Array of structures For empty tree Root's index = -1 James Tony Bob NeilDavisAdam

18 BT Array-Based Implementation public class TreeNode // node in the tree { private Object item ;// data item in the tree private int leftChild; // index to left child private int rightChild; // index to right child ……. //constructor } // end of TreeNode public abstract class BinaryTreeArrayedBased { protected final int MAX_NODES =100; protected TreeNode tree []; protected int root; // index of root protected int free; // index of next unused array location ……..//constructor and methods } // end BinaryTreeArrayedBased

19 BT Array-Based Implementation Example ItemLchild RChild O James 1 2 {root} 1 Bob3 4 2 Tony Adams Davis Neil ?-1 7 7?-1 8 8?-1 9 James Tony Bob NeilDavisAdam List of Free Nodes

20 BT Array-Based Implementation As insertion and/or deletion operations are performed, the elements of the tree might not be in consecutive locations in the array A list of free nodes should be maintained ; When a node is deleted, it is added to the free list When a node is inserted, it is removed from the free list If you know that the binary tree is complete, a simpler array-based implementation can be used that contains no Lchild, or Rchild entries.

21 BT Array-Based Implementation Since tree is complete, it maps nicely onto an array representation A B C D E F G H I J K L T: last A B DE H IJK C FG L

22 BT Array-Based Implementation For Complete Trees: A formula can be used to find the location of any node in the tree Lcild ( Tree [ i ] ) = Tree [ 2 * i + 1 ] Rcild ( Tree [ i ] ) = Tree [ 2 * i + 2 ] Parent (Tree [ i ] ) = Tree [ ( i - 1) / 2 ] Neil David Adams Tony Bob James Tony Bob NeilDavisAdam

23 Reference-Based Implementation Typical for implementing BTs Different constructors to allow defining the BT in a variety of circumstances Only the pointer to the root of the tree can be accessed by BT class clients The data structure would be private data member of a class of binary trees

24 Reference -Based Implementation public class TreeNode // node in the tree { private Object item; // data portion private TreeNode leftChildPtr; // pointer to left child private TreeNode rightChildPtr; // pointer to right child TreeNode() {}; TreeNode(Object nodeItem, TreeNode left, TreeNode right ) { } ……. } // end TreeNode class

25 Reference -Based Implementation public abstract class BinaryTreeBasis { protected TreeNode root; ……. // constructor and methods } // end BinaryTreeBasis class If the tree is empty, then root is null The root of a nonempty BT has a left subtree and right subtree, each is BT root.getRight () root.getLeft()

26 Reference -Based Implementation Example: Item LChildPtr RChildPtr Root Root of left child subtree Root of right child subtree

27 The TreeNode Class public class TreeNode { private Object item; private TreeNode leftChild; private TreeNode rightChild; public TreeNode() {} //Constructors public TreeNode(Object myElement) { item = myElement; leftChild = null; rightChild = null; } public TreeNode(Object newItem, TreeNode left, TreeNode right){ item = newItem; leftChild = left; rightChild = right; }

28 TreeNode, cont'd. public Object getItem() { return item;} public void setItem(Object newItem) {item = newItem;} public void setLeft(TreeNode left) { leftChild = left;} public TreeNode getLeft() { return leftChild;} public void setRight(TreeNode right) { rightChild = right;} public TreeNode getRight() { return rightChild;} }

29 TreeException public class TreeException extends RuntimeException { public TreeException(String s) { super (s);} } // end TreeException

30 The BinaryTreeBasis class public abstract class BinaryTreeBasis { protected TreeNode root; public BinaryTreeBasis () { root = null; } //end constructor public BinaryTreeBasis (object rootItem) { root = new TreeNode (rootItem, null, null); } //end constructor public boolean isEmpty() { //true is tree is empty return root == null; } public void makeEmpty() { //sets root of tree to null root =null; }

31 The BinaryTreeBasis class public Object getRootItem() throws TreeException { //returns element at root if it exists if (root == null) throw new TreeException ( Empty tree); else return root.getItem(); } //end getRootItem() public TreeNode getRoot() { return root; } //end getRoot() } //end class BinaryTreeBasis t: 1

32 The BinaryTree Class public class BinaryTree extend BinaryTreeBasis { //the Constructors public BinaryTree() {} public BinaryTree(Object rootItem) { super (rootItem); } //end constructor public BinaryTree(Object rootItem, BinaryTree leftTree, BinaryTree rightTree) { root = new TreeNode(rootItem, null, null); attachLeftSubTree (leftTree); attachRightSubTree (rightTree); } // end constructor all the methods go here } //end BinaryTree t: 1

33 The BinaryTree Class public void setRootItem(Object newItem) { if (root == null) root = new TreeNode (newItem, null, null); else root.setItem(newItem); } //end setRootItem tree: 2 45

34 The BinaryTree Class public void attachLeft(Object newItem) { if (!isEmpty() && root.getLeft() == null) root.setLeft(new TreeNode(newItem, null, null)); } // end attachLeft public void attachRight(Object newItem) { if (!isEmpty() && root.getRight() == null) root.setRight(new TreeNode(newItem, null, null)); } // end attachRight t 1 23 t: 1

35 The BinaryTree Class public void attachLeftSubtree(BinaryTree leftTree) throws TreeException { if (isEmpty()) throw new TreeException("Cannot attach left subtree to empty tree."); else if (root.getLeft() != null) throw new TreeException("Cannot overwrite left subtree."); else { //no empty tree, no left child root.setLeft(leftTree.root); leftTree.makeEmpty(); } //end attachLeftSubtree } t: tree1:

36 The BinaryTree Class public void attachRightSubtree(BinaryTree rightTree) throws TreeException { if (isEmpty()) throw new TreeException("Cannot attach left subtree to empty tree."); else if (root.getRight() != null) throw new TreeException("Cannot overwrite right subtree."); else { //no empty tree, no right child root.setRight(rightTree.root); rightTree.makeEmpty(); } //end attachRightSubtree }

37 The BinaryTree Class protected BinaryTree (TreeNode rootNode) { root = rootNode } //end constructor public BinaryTree detachLeftSubtree() throws TreeException { if (isEmpty()) throw new TreeException("Cannot detach empty tree."); else { // create a tree points to the leftsubtree BinaryTree leftTree; leftTree = new BinaryTree (root.getLeft()); root.setLeft (null); return leftTree; } } //end detachLeftSubtree }

38 The BinaryTree Class public BinaryTree detachRightSubtree() throws TreeException { if (isEmpty()) throw new TreeException("Cannot detach empty tree."); else { // create a tree points to the rightsubtree BinaryTree rightTree; rightTree = new BinaryTree (root.getRight()); root.setRight (null); return rightTree; } } //end detachRightSubtree }

39 preOrderPrint( ) public void preOrderPrint(TreeNode rootNode) throws TreeException { if (rootNode!=null) { System.out.print(rootNode.getItem() + " "); preOrderPrint(rootNode.getLeft()); preOrderPrint(rootNode.getRight()); } Print tree using preorder traversal: t:

40 inOrderPrint() Print tree using inorder traversal: t: public void inOrderPrint(TreeNode rootNode) throws TreeException { if (rootNode!=null) { inOrderPrint(rootNode.getLeft()); System.out.print(rootNode.getItem() + " "); inOrderPrint(rootNode.getRight()); }

41 postOrderPrint( ) Print tree using postOrder traversal: t: public void postOrderPrint(TreeNode rootNode) throws TreeException { if (rootNode!=null) { postOrderPrint(rootNode.getLeft()); postOrderPrint(rootNode.getRight()); System.out.print(rootNode.getItem() + " "); }

42 An Example Program public class BinaryTreeTest { public static void main (String args[]) throws BinaryTreeException { BinaryTree t = new BinaryTree(new Integer(1)); System.out.println("Element at root of tree = " + t.getRootElement()); System.out.println("Initial tree is: "); t.reOrderPrint(t.getRoot()); System.out.println(); BinaryTree tree1 = new BinaryTree(new Integer(2)); tree1.attachLeft(new Integer(4)); tree1.attachRight(new Integer(5)); System.out.println("Tree1 is: "); tree1.preOrderPrint(tree1.getRoot()); System.out.println(); tree1: 2 45 t: 1

43 Example, cont'd. BinaryTree tree2 = new BinaryTree(new Integer(6)); tree2.attachLeft(new Integer(7)); tree2.attachRight(new Integer(8)); System.out.println("tree2 is: "); tree2.preOrderPrint(tree2.getRoot()); System.out.println(); BinaryTree tree3 = new BinaryTree(new Integer(3)); tree3.attachLeftSubtree(tree2); System.out.println("Tree3 is: "); tree3.preOrderPrint(tree3.getRoot()); System.out.println(); t.attachLeftSubtree(tree1); t.attachRightSubtree(tree3); System.out.println("Final tree is: "); t.preOrderPrint(t.getRoot()); System.out.println(); } tree2: 6 78 tree3: t:

44 Expression Tree Given a math expression, there exists a unique corresponding expression tree. 5+ (6* (8-6)) + 5* 6- 86

45 Preorder Of Expression Tree + a b - c d + e f * / Gives prefix form of expression! /*+ab-cd+ef

46 Inorder By Projection a bc d e f g hi j gdhbeia f jc

47 Inorder Of Expression Tree + a b - c d + e f * / Gives infix form of expression (sans parentheses)! ea+b*cd/+f-

48 Postorder Of Expression Tree + a b - c d + e f * / Gives postfix form of expression! ab+cd-*ef+/