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

Slides:



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

Chapter 7. Binary Search Trees
Postorder traversal - Ed. 2. and 3.: Chapter 6 – - Ed. 4.: Chapter 7 -
CSC 205 – Java Programming II Lecture 35 April 17, 2002.
1 Nell Dale Chapter 9 Trees Plus Modified from the slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus C++ Plus Data Structures.
1 A Two-Level Binary Expression ‘-’ ‘8’ ‘5’ treePtr INORDER TRAVERSAL : has value 3 PREORDER TRAVERSAL: POSTORDER TRAVERSAL: 8 5 -
© 2006 Pearson Addison-Wesley. All rights reserved11 B-1 Chapter 11 (continued) Trees.
Trees. Terminology Trees are hierarchical –“parent-child” relationship A is the parent of B B is a child of A B and C are siblings Generalized to ancestor.
Kymberly Fergusson CSE1303 Part A Data Structures and Algorithms Summer Semester 2003 Lecture A12 – Binary Trees.
© 2006 Pearson Addison-Wesley. All rights reserved11 A-1 Chapter 11 Trees.
Razdan CST230http://dcst2.east.asu.edu/~razdan/cst230/ Razdan with contribution from others 1 Chapter 9 Trees Anshuman Razdan Div of Computing Studies.
Kymberly Fergusson CSE1303 Part A Data Structures and Algorithms Summer Semester 2003 Lecture A12 – Binary Trees.
Binary Tree Properties & Representation. Minimum Number Of Nodes Minimum number of nodes in a binary tree whose height is h. At least one node at each.
1 abstract containers hierarchical (1 to many) graph (many to many) first ith last sequence/linear (1 to 1) set.
Trees-part1. Objectives Understand tree terminology Understand and implement tree traversals Define the binary search tree property Implement binary search.
Marc Smith and Jim Ten Eyck
Binary and Other Trees CSE, POSTECH. 2 2 Linear Lists and Trees Linear lists are useful for serially ordered data – (e 1,e 2,e 3,…,e n ) – Days of week.
1 Nell Dale Chapter 9 Trees Plus Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus C++ Plus Data Structures.
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.
Thought for the Day “To become truly great, one has to stand with people, not above them.” – Charles de Montesquieu.
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.
CS 1031 Tree Traversal Techniques; Heaps Tree Traversal Concept Tree Traversal Techniques: Preorder, Inorder, Postorder Full Trees Almost Complete Trees.
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,
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver. 5.0.
© 2011 Pearson Addison-Wesley. All rights reserved 11 B-1 Chapter 11 (continued) Trees.
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.
Binary Trees. 2 Parts of a binary tree A binary tree is composed of zero or more nodes In Java, a reference to a binary tree may be null Each node contains:
1 Trees, Trees, and More Trees. 2 By looking at forests of terms, awesome animations, and complete examples, we hope to get at the root of trees. Hopefully,
1 Binary Trees (7.3) CSE 2011 Winter November 2015.
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.
COSC2007 Data Structures II Chapter 11 Trees IV. 2 Topics ADT BST Implementations Efficiency TreeSort Save/Restore into/from file General Trees.
Topics Definition and Application of Binary Trees Binary Search Tree Operations.
Advance Data Structure 1 College Of Mathematic & Computer Sciences 1 Computer Sciences Department م. م علي عبد الكريم حبيب.
Lecture - 10 on Data Structures. 6:05:57 PM Prepared by, Jesmin Akhter, Lecturer, IIT,JU.
© University of Auckland Trees – (cont.) CS 220 Data Structures & Algorithms Dr. Ian Watson.
1 CMPSCI 187 Computer Science 187 Introduction to Introduction to Programming with Data Structures Lecture 16: Trees Announcements 1.Programming project.
Trees Chapter 10. CS 308 2Chapter Trees Preview: Preview: The data organizations presented in previous chapters are linear, in that items are one.
© 2006 Pearson Addison-Wesley. All rights reserved11 A-1 Chapter 11 Trees.
Binary Trees. 2 Parts of a binary tree A binary tree is composed of zero or more nodes In Java, a reference to a binary tree may be null Each node contains:
Binary Tree.
CSC 205 Java Programming II Lecture 26 Traversing Binary Tree.
CMPSCI Introduction to Introduction to Programming with Data Structures Lecture 18 Binary Search Trees and Priority Queues Lecture 18 Binary Search.
1 Trees. 2 Trees Trees. Binary Trees Tree Traversal.
Chapter 05 Trees (Part II). Array Representation We can use an array to represent a complete binary tree. Lemma 5.4 ▫If a complete binary tree with.
Binary Trees.
Binary Trees.
Trees Chapter 11 (continued)
Trees Chapter 11 (continued)
CS 302 Data Structures Trees.
Chapter 11 Trees © 2011 Pearson Addison-Wesley. All rights reserved.
Csc 2720 Instructor: Zhuojun Duan
Ch. 11 Trees 사실을 많이 아는 것 보다는 이론적 틀이 중요하고, 기억력보다는 생각하는 법이 더 중요하다.
Binary Trees.
Binary Tree Traversal Methods
Binary Tree Traversal Methods
Binary Trees.
Binary Trees.
Binary Tree Traversal Methods
Trees Chapter 10.
Binary Trees.
Chapter 11 Trees © 2011 Pearson Addison-Wesley. All rights reserved.
Binary Tree Traversal Methods
C++ Plus Data Structures
CSC 205 – Java Programming II
COSC2007 Data Structures II
Presentation transcript:

COSC2007 Data Structures II Chapter 11 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 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?

5 BT Traversal Visit every node in a BT exactly once. Each visit performs the same operations on each node Natural traversal orders: Pre-order Node-Left-Right (NLR) In-order Left-Node-Right (LNR) Post-order Left-Right-Node (LRN)

6 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

7 Pre-order Traversal Pseudocode preorder (binaryTree:BinaryTree ) // Traverses the binary tree binaryTree in preorder. // Assumes that “visit a node” means to display the node’s 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 ) }

8 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

9 In-order Traversal Pseudocode inorder (binaryTree:BinaryTree ) // Traverses the binary tree binaryTree in inorder. // Assumes that “visit a node” means to display the node’s 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 ) }

10 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

11 Post-order Traversal Pseudocode postorder (binaryTree:BinaryTree ) // Traverses the binary tree binaryTree in postorder. // Assumes that “visit a node” means to display the node’s 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 }

12 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

13 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 index? James Tony Bob NeilDavisAdam

14 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

15 BT Array-Based Implementation Array based is only good for complete tree 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

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

17 Reference-Based Implementation Typical for implementing BTs 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

18 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

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

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

21 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; }

22 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;} }

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

24 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; }

25 The BinaryTreeBasis class public Object getRootItem() throws TreeException { 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

26 The BinaryTree Class public class BinaryTree extends 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

27 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

28 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

29 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:

30 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 }

31 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 }

32 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 }

33 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:

34 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()); }

35 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() + " "); }

36 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.preOrderPrint(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

37 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:

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

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

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

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