Copyright  1997 Oxford University Press All Rights Reserved

Slides:



Advertisements
Similar presentations
Chapter 7. Binary Search Trees
Advertisements

Binary Trees, Binary Search Trees COMP171 Fall 2006.
© 2006 Pearson Addison-Wesley. All rights reserved11 B-1 Chapter 11 (continued) Trees.
Fall 2007CS 2251 Trees Chapter 8. Fall 2007CS 2252 Chapter Objectives To learn how to use a tree to represent a hierarchical organization of information.
Trees, Binary Trees, and Binary Search Trees COMP171.
Data Structures Data Structures Topic #8. Today’s Agenda Continue Discussing Table Abstractions But, this time, let’s talk about them in terms of new.
Lec 15 April 9 Topics: l binary Trees l expression trees Binary Search Trees (Chapter 5 of text)
Fundamentals of Python: From First Programs Through Data Structures
Data Structures Using C++ 2E Chapter 11 Binary Trees and B-Trees.
Marc Smith and Jim Ten Eyck
Binary Search Trees Chapter 6.
More Trees COL 106 Amit Kumar and Shweta Agrawal Most slides courtesy : Douglas Wilhelm Harder, MMath, UWaterloo
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.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Templatized Tree.
(c) University of Washington20d-1 CSC 143 Java Applications of Trees.
Trees Chapter 15 Data Structures and Problem Solving with C++: Walls and Mirrors, Carrano and Henry, © 2013.
CS Data Structures Chapter 15 Trees Mehmet H Gunes
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.
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,
Binary Trees Chapter 10. Introduction Previous chapter considered linked lists –nodes connected by two or more links We seek to organize data in a linked.
Spring 2010CS 2251 Trees Chapter 6. Spring 2010CS 2252 Chapter Objectives Learn to use a tree to represent a hierarchical organization of information.
INTRODUCTION TO BINARY TREES P SORTING  Review of Linear Search: –again, begin with first element and search through list until finding element,
A Binary Search Tree Binary Search Trees.
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.
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.
Trees, Binary Trees, and Binary Search Trees COMP171.
TREES. What is a tree ? An Abstract Data Type which emulates a tree structure with a set of linked nodes The nodes within a tree are organized in a hierarchical.
Lec 15 Oct 18 Binary Search Trees (Chapter 5 of text)
Slide 1 Linked Data Structures. Slide 2 Learning Objectives  Nodes and Linked Lists  Creating, searching  Linked List Applications  Stacks, queues.
Copyright © 2002 Pearson Education, Inc. Slide 1.
CSC 143 Trees [Chapter 10].
CE 221 Data Structures and Algorithms Chapter 4: Trees (Binary) Text: Read Weiss, §4.1 – 4.2 1Izmir University of Economics.
Binary Trees Chapter 10. Introduction Previous chapter considered linked lists –nodes connected by two or more links We seek to organize data in a linked.
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. 1 Chapter 19 Binary Search Trees.
Tree Traversals, TreeSort 20 February Expression Tree Leaves are operands Interior nodes are operators A binary tree to represent (A - B) + C.
CMSC 341 Introduction to Trees. 2/21/20062 Tree ADT Tree definition –A tree is a set of nodes which may be empty –If not empty, then there is a distinguished.
1/14/20161 BST Operations Data Structures Ananda Gunawardena.
1 Chapter 4 Trees Basic concept How tree are used to implement the file system How tree can be used to evaluate arithmetic expressions How to use trees.
ADT Binary Search Tree Ellen Walker CPSC 201 Data Structures Hiram College.
Prof. Amr Goneid, AUC1 CSCE 210 Data Structures and Algorithms Prof. Amr Goneid AUC Part 6. Dictionaries(3): Binary Search Trees.
Trees Chapter 10. CS 308 2Chapter Trees Preview: Preview: The data organizations presented in previous chapters are linear, in that items are one.
353 3/30/98 CSE 143 Trees [Sections , 13.6,13.8]
CS 240Chapter 10 – TreesPage Chapter 10 Trees The tree abstract data type provides a hierarchical to the representation of certain types of relationships.
1 Binary Search Trees. 2 Binary Search Trees Binary Search Trees The Binary Search Tree (BST) Search, Insertion and Traversal of BST Removal of nodes.
CS 201 Data Structures and Algorithms
Trees Chapter 15.
Data Structure and Algorithms
Trees Chapter 11 (continued)
Trees Chapter 11 (continued)
Binary Search Tree (BST)
CS 302 Data Structures Trees.
CMSC 341 Introduction to Trees.
Data Structures Using C++ 2E
Binary Tree and General Tree
Binary Tree and General Tree
Chapter 7 TREES.
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.
Lecture 12 CS203 1.
General Trees & Binary Trees
CE 221 Data Structures and Algorithms
Binary Trees, Binary Search Trees
Trees Chapter 10.
CE 221 Data Structures and Algorithms
Trees.
CSC 143 Java Applications of Trees.
CSC 143 Java Trees.
A Binary Search Tree Implementation
Binary Trees, Binary Search Trees
Data Structures Using C++ 2E
Chapter 11 Trees © 2011 Pearson Addison-Wesley. All rights reserved.
Presentation transcript:

Copyright  1997 Oxford University Press All Rights Reserved Figures from Chapter 11 of Data Structures via C++ Objects by Evolution A. Michael Berman Copyright  1997 Oxford University Press All Rights Reserved

Copyright  1997 Oxford University Press All Rights Reserved Chapter 11 Trees Overview Trees are a flexible data structure useful for solving a wide range of problems. 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Copyright  1997 Oxford University Press All Rights Reserved Chapter Objectives 1. Trees represent data in a hierarchical manner. 2. Binary search trees allow rapid retrieval by key, plus in-order processing. 3. Inheritance can be used to model “is-a” relationships and support code reuse. 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Copyright  1997 Oxford University Press All Rights Reserved Figure 11-1: A Tree A B C D E F 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Copyright  1997 Oxford University Press All Rights Reserved Definition 11-1 A binary tree is either: 1. an empty tree; or 2. consists of a node, called a root, and two children, left and right, each of which are themselves binary trees. 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Copyright  1997 Oxford University Press All Rights Reserved Figure 11-2: A Binary Tree 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Figure 11-3: Two distinct Binary Trees 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Figure 11-4: Expression tree for 3 + 7  2 - 1 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Figure 11-5: Expression tree after first subtree eliminated  + 1 14 3 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Figure 11-6: Expression tree after second subtree eliminated  17 1 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Figure 11-7: Final value of expression tree 16 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Copyright  1997 Oxford University Press All Rights Reserved Exercise 11-1 There’s one possible empty binary tree, and one binary tree containing a single node. When you get to two nodes, there’s two possible binary trees -- a root with a left subtree, and a root with a right subtree. Draw the five possible binary tree with 3 nodes. 11-2 How many binary trees are with 4 nodes? 5 nodes? can you infer the formula for trees with n nodes? 11-3 Create an expression tree for the following expression: 6 * 4 / 2 + 7 - 5 * 3 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Copyright  1997 Oxford University Press All Rights Reserved Exercises 11-4 Evaluate the expression tree created in Exercise 11-3 on Page 273. 11-5 Develop (recursive) algorithms for the following: a. determine the number of nodes in a tree; b. determine the degree of a tree; c. determine the depth of a tree. 11-6 Explain the difference between a Binary Tree (as defined in Definition 11-1 on Page 269) and a tree of degree 2. 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Copyright  1997 Oxford University Press All Rights Reserved ADT 11-1 Characteristics • A Binary Tree ADT T stores data of some type (btElementType), using a binary tree as defined in Definition 11-1 on Page 269. Operations bool T.isEmpty() Precondition: None. Postcondition: None. Returns: true if and only if T is an empty tree 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Copyright  1997 Oxford University Press All Rights Reserved ADT 11-1 btElementType T.getData() Precondition: !T.isEmpty() Postcondition: None. Returns: The data associated with the root of the tree. void T.insert(btElementType d) Postcondition: T.getData()==d 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Copyright  1997 Oxford University Press All Rights Reserved ADT 11-1 BinaryTree T.left() Precondition: !T.isEmpty() Postcondition: None Returns: The left child of T BinaryTree T.right() Returns: The right child of T 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Copyright  1997 Oxford University Press All Rights Reserved ADT 11-1 void T.makeLeft() Precondition: !T.isEmpty();T.left().isEmpty() Postcondition: T.left() == T1 void T.makeRight() Postcondition: T.right() == T1 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Copyright  1997 Oxford University Press All Rights Reserved Code Example 11-1 // cx11-1.h // Code Example 11-1: Interface File: Binary Tree #ifndef __MB_CX11_1__ #define __MB_CX11_1__ #include "dslib.h" template < class btElementType > class BinaryTree { public: BinaryTree(); bool isEmpty() const; // Precondition: None. // Postcondition: None. // Returns: true if and only if T is an empty tree 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Copyright  1997 Oxford University Press All Rights Reserved Code Example 11-1 btElementType getData() const; // getData is an accessor // Precondition: !this->isEmpty() // Postcondition: None // Returns: The data associated with the root of the tree void insert(const btElementType & d); // Precondition: none // Postconditions: this->getData() == d; !this->isEmpty() BinaryTree * left(); // Returns: (a pointer to) the left child of T BinaryTree * right(); // Returns: (a pointer to) the right child of T 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Copyright  1997 Oxford University Press All Rights Reserved Code Example 11-1 void makeLeft(BinaryTree * T1); // Precondition: !this->isEmpty(); this->left()->isEmpty() // Postcondition: this->left() == T1 void makeRight(BinaryTree * T1); // Precondition: !this->isEmpty(); this->right()->isEmpty() // Postcondition: this->right() == T1 private: bool nullTree; btElementType treeData; BinaryTree * leftTree; BinaryTree * rightTree; }; #endif 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Copyright  1997 Oxford University Press All Rights Reserved Code Example 11-2 // cx11-2.cpp // Code Example 11-2: Implementation File: Binary Tree #include "cx11-1.h" template < class btElementType > BinaryTree < btElementType > :: BinaryTree() { nullTree = true; leftTree = 0; rightTree = 0; } 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Copyright  1997 Oxford University Press All Rights Reserved Code Example 11-2 template < class btElementType > bool BinaryTree < btElementType > :: isEmpty() const { return nullTree; } btElementType BinaryTree < btElementType > :: getData() const assert(!isEmpty()); return treeData; 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Copyright  1997 Oxford University Press All Rights Reserved Code Example 11-2 template < class btElementType > void BinaryTree < btElementType > :: insert(const btElementType & d) { treeData = d; if (nullTree) { nullTree = false; leftTree = new BinaryTree; rightTree = new BinaryTree; } 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Copyright  1997 Oxford University Press All Rights Reserved Code Example 11-2 template < class btElementType > BinaryTree < btElementType > * BinaryTree < btElementType > :: left() { assert(!isEmpty()); return leftTree; } BinaryTree < btElementType > :: right() return rightTree; 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Copyright  1997 Oxford University Press All Rights Reserved Code Example 11-2 template < class btElementType > void BinaryTree < btElementType > :: makeLeft(BinaryTree * T1) { assert(!isEmpty()); assert(left()->isEmpty()); delete left(); leftTree = T1; } 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Copyright  1997 Oxford University Press All Rights Reserved Code Example 11-2 template < class btElementType > void BinaryTree < btElementType > :: makeRight(BinaryTree * T1) { assert(!isEmpty()); assert(right()->isEmpty()); delete right(); rightTree = T1; } 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Figure 11-8: The operation of Code Example 11-3 B C F E D bt6 bt3 bt1 bt2 bt5 bt4 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Copyright  1997 Oxford University Press All Rights Reserved Code Example 11-3 // cx11-3.cpp // Code Example 11-3: Simple Client for Binary Tree #include "cx11-1.h" #include <iostream.h> int main() { typedef BinaryTree < char > charTree; typedef charTree * charTreePtr; // Create tree from Figure 11-2 // Create left subtree (rooted at B) 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Copyright  1997 Oxford University Press All Rights Reserved Code Example 11-3 // Create B's left subtree charTreePtr bt1(new charTree); bt1->insert('D'); // Create B's right subtree charTreePtr bt2(new charTree); bt2->insert('E'); // Create node containing B, and link // up to subtrees charTreePtr bt3(new charTree); bt3->insert('B'); bt3->makeLeft(bt1); bt3->makeRight(bt2); // ** done creating left subtree 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Copyright  1997 Oxford University Press All Rights Reserved Code Example 11-3 // Create right subtree // Create C's right subtree charTreePtr bt4(new charTree); bt4->insert('F'); // Create node containing C, and link // up its right subtree charTreePtr bt5(new charTree); bt5->insert('C'); bt5->makeRight(bt4); // ** done creating right subtree 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Copyright  1997 Oxford University Press All Rights Reserved Code Example 11-3 // Create the root of the tree, and link together charTreePtr bt6(new charTree); bt6->insert('A'); bt6->makeLeft(bt3); bt6->makeRight(bt5); // print out the root cout << "Root contains: " << bt6->getData() << endl; // print out root of left subtree cout << "Left subtree root: " << bt6->left()->getData() << endl; // print out root of right subtree cout << "Right subtree root: " << bt6->right()->getData() << endl; 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Copyright  1997 Oxford University Press All Rights Reserved Code Example 11-3 // print out leftmost child in tree cout << "Leftmost child is: " << bt6->left()->left()->getData() << endl; // print out rightmost child in tree cout << "Rightmost child is: " << bt6->right()->right()->getData() << endl; return 0; } 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Copyright  1997 Oxford University Press All Rights Reserved Code Example 11-4 // cx11-4.h // Code Example 11-4: Expression Tree: Header Files #ifndef __MB_CX11_4__ #define __MB_CX11_4__ #include "dslib.h" enum evalNodeType { evalOperator, evalOperand }; enum evalOperatorType { add, subtract, multiply, divide }; class evalNode { 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Copyright  1997 Oxford University Press All Rights Reserved Code Example 11-4 public: evalNode(double d); evalNode(evalOperatorType op); evalNodeType getType() const; double getOperand() const; evalOperatorType getOperator() const; private: evalNodeType nodeType; double nodeOperand; evalOperatorType nodeOperator; }; 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Copyright  1997 Oxford University Press All Rights Reserved Code Example 11-4 typedef evalNode * evalNodePtr; // Pointer to an evalNode #include "cx11-1.h" // binary tree header file#include "cx11-2.cpp" // An evalTree is a BinaryTree of pointers to evalNodes typedef BinaryTree < evalNodePtr > evalTree; typedef evalTree * evalTreePtr; // Pointer to an evalTree double evaluateTree(evalTreePtr t); #endif 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Copyright  1997 Oxford University Press All Rights Reserved Code Example 11-5 // cx11-5.cpp // Code Example 11-5: Implementation file: expression tree #include "dslib.h" #include "cx11-4.h" // header file for expression tree evalNode::evalNode(double d) { nodeType = evalOperand; nodeOperand = d; } evalNode::evalNode(evalOperatorType op) nodeType = evalOperator; nodeOperator = op; 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Copyright  1997 Oxford University Press All Rights Reserved Code Example 11-5 evalNodeType evalNode::getType() const { return nodeType; } double evalNode::getOperand() const assert(nodeType == evalOperand); return nodeOperand; 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Copyright  1997 Oxford University Press All Rights Reserved Code Example 11-5 evalOperatorType evalNode::getOperator() const { assert(nodeType == evalOperator); return nodeOperator; } double evaluateTree(evalTreePtr t) assert(!t->isEmpty()); evalNodePtr rootNodePtr = t->getData(); if (rootNodePtr->getType() == evalOperand) return rootNodePtr->getOperand(); 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Copyright  1997 Oxford University Press All Rights Reserved Code Example 11-5 else { double left(evaluateTree(t->left())); double right(evaluateTree(t->right())); switch(rootNodePtr->getOperator()) { case add: return left + right; case subtract: return left - right; case multiply: return left * right; case divide: assert(right); return left / right; } 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Copyright  1997 Oxford University Press All Rights Reserved Code Example 11-6 // cx11-6.cpp // Code Example 11-6: Using the expression tree #include "dslib.h" #include "cx11-4.h" // Expression tree header file int main() { evalTreePtr et1(new evalTree); et1->insert(new evalNode(subtract)); evalTreePtr et2(new evalTree); et2->insert(new evalNode(add)); evalTreePtr et3(new evalTree); et3->insert(new evalNode(1.0)); 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Copyright  1997 Oxford University Press All Rights Reserved Code Example 11-6 et1->makeLeft(et2); et1->makeRight(et3); evalTreePtr et4(new evalTree); et4->insert(new evalNode(3.0)); evalTreePtr et5(new evalTree); et5->insert(new evalNode(multiply)); et2->makeLeft(et4); et2->makeRight(et5); evalTreePtr et6(new evalTree); et6->insert(new evalNode(7.0)); 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Copyright  1997 Oxford University Press All Rights Reserved Code Example 11-6 evalTreePtr et7(new evalTree); et7->insert(new evalNode(2.0)); et5->makeLeft(et6); et5->makeRight(et7); cout << evaluateTree(et1) << endl; return 0; } 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Copyright  1997 Oxford University Press All Rights Reserved Exercises 11-7 Using Code Example 11-6 as a model, write and test a program to evaluate the expression: 6 * 4 / 2 + 7 - 6 * 3 11-8 Explicitly representing the empty trees in a Binary Tree requires extra space that is not really needed. In percentage terms, how much extra space is used? Describe in general how you could modify the implementation to eliminate this extra space. What would be the pros and cons of this alternate implementation? 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Copyright  1997 Oxford University Press All Rights Reserved Algorithms 11-1 if the tree is not empty visit the root preOrderTraverse(left child) preOrderTraverse(right child) 11-2 if the tree is not empty inOrderTraverse(left child) inOrderTraverse(right child) 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Copyright  1997 Oxford University Press All Rights Reserved Algorithm 11-3 if the tree is not empty postOrderTraverse(left child) postOrderTraverse(right child) visit the root 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Figure 11-9: Sample tree to illustrate tree traversal 2 3 4 5 6 7 8 9 10 11 12 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Figure 11-10: Tree after four nodes visited in preorder traversal 2 3 5 10 4 8 9 6 11 12 7 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Copyright  1997 Oxford University Press All Rights Reserved Figure 11-11: Tree after left subtree of root visited using preorder traversal 1 2 3 5 10 4 8 9 6 11 12 7 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Figure 11-12: Tree after completed preorder traversal 8 2 2 3 3 6 9 12 4 5 6 7 11 4 8 9 5 7 10 10 11 12 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Figure 11-13: Tree visited using inorder traversal 2 3 5 10 4 8 9 6 11 12 7 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Figure 11-14: Tree visited using postorder traversal 12 1 6 2 11 3 3 4 5 5 9 6 10 7 1 8 9 2 4 10 7 11 12 8 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Figure 11-15: Expression Tree for 3 + 7  2 - 1  + 1 14 3 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Copyright  1997 Oxford University Press All Rights Reserved Code Example 11-7 // cx11-7.cpp // Code Example 11-7: Binary Tree Traversals #include "dslib.h" #include "cx11-1.h" typedef BinaryTree < int > btint; typedef btint * btintp; void preOrderTraverse(btintp bt) { if (!bt->isEmpty()) { // visit tree cout << bt->getData() << '\t'; 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Copyright  1997 Oxford University Press All Rights Reserved Code Example 11-7 // traverse left child preOrderTraverse(bt->left()); // traverse right child preOrderTraverse(bt->right()); } void inOrderTraverse(btintp bt) { if (!bt->isEmpty()) { inOrderTraverse(bt->left()); // visit tree cout << bt->getData() << '\t'; inOrderTraverse(bt->right()); 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Copyright  1997 Oxford University Press All Rights Reserved Code Example 11-8 // cx11-8.cpp // Code Example 11-8: Binary Tree Traversal #include "dslib.h" #include "cx11-1.h" typedef BinaryTree < int > btint; typedef btint * btintp; void preOrderTraverse(btintp bt, void visit(btintp)) { if (!bt->isEmpty()) { // visit tree (* visit)(bt); 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Copyright  1997 Oxford University Press All Rights Reserved Code Example 11-8 // traverse left child preOrderTraverse(bt->left(), visit); // traverse right child preOrderTraverse(bt->right(), visit); } void inOrderTraverse(btintp bt, void visit(btintp)) { if (!bt->isEmpty()) { inOrderTraverse(bt->left(), visit); // visit tree (* visit)(bt); 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Copyright  1997 Oxford University Press All Rights Reserved Code Example 11-8 //traverse right child inOrderTraverse(bt->right(), visit); } void visit(btintp bt) { cout << bt->getData() << '\t'; 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Copyright  1997 Oxford University Press All Rights Reserved Exercise 11-9 Practice your three tree traversals, using the tree shown in Figure 11-16 on Page 291. 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Figure 11-16: Sample tree for Exercise 11-9 B C D E F G H I J K L M N 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Copyright  1997 Oxford University Press All Rights Reserved Exercise 11-10 11-10 Given an in-order traversal sequence, plus either a pre-order or post-order sequence, it’s possible to reconstruct the tree they were traversing. For the following sequences, reconstruct the tree that they represent: pre-order: 3 2 1 5 4 8 7 6 9 10 13 12 11 14 in-order: 1 2 4 5 3 6 7 9 8 10 11 12 14 13 (Hint: You know that 3 is the head (why?), so the nodes 1 2 4 5 are in the left subtree, and the nodes following 3 are in the right subtree. Applying this recursively will give you the entire tree.) 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Copyright  1997 Oxford University Press All Rights Reserved Exercise 11-10 For the following expression: 17 * 3 + 2 - (10 * 9 / 3) + 3 * 4 a. Draw the expression tree corresponding to the expression. b. Convert the expression to pre-fix notation. c. Perform a pre-order traversal of the tree and confirm that it’s the same as your prefix expression in part b. 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Copyright  1997 Oxford University Press All Rights Reserved Exercises 11-11 Write a program that creates a small tree (say, 7 nodes), then calls the traversal functions in Code Example 11-7 on Page 288 to print out traversals. Before you test the program, draw your tree and perform the traversals yourself, and compare the answers you get with the ones the program prints out. 11-12 Add a function postOrderTraversal to Code Example 11-7 on Page 288. Write a driver to test your function for correct operation. 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Copyright  1997 Oxford University Press All Rights Reserved Exercise 11-13 Write a function that sends the data field of a tree to a disk file. Write a program that creates a small tree, calls the tree traversal from Code Example 11-8 on Page 289, and passes it a pointer to your function. 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Figure 11-17: A Binary Search Tree 10 26 14 6 20 34 11 31 37 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Copyright  1997 Oxford University Press All Rights Reserved Figure 11-18: A binary tree that is not a BST because BST invariant is violated 17 10 26 14 6 15 34 11 31 37 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Copyright  1997 Oxford University Press All Rights Reserved ADT 11-12 Characteristics * A Binary Search Tree ADT T stores data of some type (btElementType), using a binary search tree as defined in Definition 11-2 on Page 292. Prerequisites The data type btElementType must implement the < and == operators. 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Copyright  1997 Oxford University Press All Rights Reserved Figure 11-19: A binary tree that is not a BST because one subtree is not a BST 17 10 26 14 6 20 28 11 31 37 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Copyright  1997 Oxford University Press All Rights Reserved ADT 11-2 Operations bool T.isEmpty() Precondition: None. Postcondition: None. Returns: true if and only if T is an empty tree. btElementType T.getData() Precondition: !T.isEmpty() Returns: The data associated with the root of the tree 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Copyright  1997 Oxford University Press All Rights Reserved ADT 11-2 void T.insert(btElementType d) Precondition: !T.isEmpty(); T meets the BST invariant Postcondition: T.retrieve(d).getData() == d; T meets the BST invariant. BinaryTree T.retrieve(btElementType d) Precondition: T meets the BST invariant. Postcondition: T meets the BST invariant. Returns: if T contains a node with data d, then T.retrieve(d).getData() == d; otherwise, T.retrieve(d).isEmpty(). 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Copyright  1997 Oxford University Press All Rights Reserved ADT 11-2 BinaryTree T.left() Precondition: !T.isEmpty() Postcondtion: None. Returns: The left child of T BinaryTree T.right() Returns: The right child of T 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Copyright  1997 Oxford University Press All Rights Reserved Figure 11-20: A Binary Search Tree showing position where 12 would be inserted 17 10 26 6 14 20 28 11 31 37 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Figure 11-21: The Binary Search Tree after 12 inserted 17 10 26 6 14 20 28 11 31 37 12 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Copyright  1997 Oxford University Press All Rights Reserved Code Example 11-9 // cx11-9.h // Code Example 11-9: Interface File: Binary Search Trees #ifndef __MB_CX11_9__ #define __MB_CX11_9__ #include "dslib.h" template < class btElementType > class BST { public: BST(); bool isEmpty() const; // Precondition: None. // Postcondition: None. // Returns: true if and only if T is an empty tree 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Copyright  1997 Oxford University Press All Rights Reserved Code Example 11-9 btElementType getData() const; // Precondition: !this->isEmpty() // Postcondition: None // Returns: The data associated with the root of the tree void insert(const btElementType & d); // Precondition: if d is a left child, then d must be < parent->getData(); // if d is a right child, then d must be > parent->getData(); // Postconditions: T->retrieve(k)->getData() == d BST * retrieve(const btElementType & d); // Precondition: none // Postcondition: none // Returns: if T contains a node matching d, then // T->retrieve(d)->getData() == d; otherwise, T->isEmpty() BST * left(); 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Copyright  1997 Oxford University Press All Rights Reserved Code Example 11-9 // Precondition: !this->isEmpty() // Postcondition: None // Returns: (a pointer to) the left child of T BST * right(); // Returns: (a pointer to) the right child of T private: bool nullTree; btElementType treeData; BST * leftTree; BST * rightTree; }; #endif 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Copyright  1997 Oxford University Press All Rights Reserved Code Example 11-10 // cx11-10.cpp // Code Example 11-10: Implementation File: Binary Tree #include "cx11-9.h" template < class btElementType > BST < btElementType > :: BST() { nullTree = true; leftTree = 0; rightTree = 0; } 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Copyright  1997 Oxford University Press All Rights Reserved Code Example 11-10 template < class btElementType > bool BST < btElementType > :: isEmpty() const { return nullTree; } btElementType BST < btElementType > :: getData() const assert(!isEmpty()); return treeData; 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Copyright  1997 Oxford University Press All Rights Reserved Code Example 11-10 template < class btElementType > void BST < btElementType > :: insert(const btElementType & d) { if (nullTree) { nullTree = false; leftTree = new BST; rightTree = new BST; treeData = d; } else if (d == treeData) ; // do nothing -- it's already here! else if (d < treeData) leftTree->insert(d); else rightTree->insert(d); 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Copyright  1997 Oxford University Press All Rights Reserved Code Example 11-10 template < class btElementType > BST < btElementType > * BST < btElementType > :: retrieve(const btElementType & d) { if (nullTree || d == treeData) // return a pointer to the tree for which retrieve was called return this; else if (d < treeData) return leftTree->retrieve(d); else return rightTree->retrieve(d); } 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Copyright  1997 Oxford University Press All Rights Reserved Code Example 11-10 template < class btElementType > BST < btElementType > * BST < btElementType > :: left() { assert(!isEmpty()); return leftTree; } BST < btElementType > :: right() return rightTree; 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Copyright  1997 Oxford University Press All Rights Reserved Code Example 11-11 // cx11-11.cpp // Code Example 11-11: Sample Client of BST #include "cx11-9.h" int main() { typedef BST < int > intBST; typedef intBST * intBSTPtr; intBSTPtr b(new intBST); b->insert(17); b->insert(10); b->insert(26); b->insert(6); b->insert(14); 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Copyright  1997 Oxford University Press All Rights Reserved Code Example 11-11 b->insert(20); b->insert(28); b->insert(11); b->insert(31); b->insert(37); b->insert(12); // is 11 in the tree? intBSTPtr get11(b->retrieve(11)); if (get11->isEmpty()) cout << "11 not found.\n"; else cout << "11 found.\n"; // is 13 in the tree? 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Copyright  1997 Oxford University Press All Rights Reserved Code Example 11-11 intBSTPtr get13(b->retrieve(13)); if (get13->isEmpty()) cout << "13 not found.\n"; else cout << "13 found.\n"; return 0; } 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Copyright  1997 Oxford University Press All Rights Reserved Exercises 11-14 Trace the process of inserting the following items into the BST on Figure 11-20 on Page 295, and draw the resulting tree: 21, 30, 50, 34 11-15 Draw the BST that’s created when the following items are added to an initially empty tree, in the order given: 17, 3, 45, 55, 33, 1, 29, 30, 20, 5 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Copyright  1997 Oxford University Press All Rights Reserved Exercises 11-16 Give a possible order that items might have been inserted to create the tree in Figure 11-17 on Page 293. 11-17 The BST as shown in the example doesn’t meet all our needs, because it contains only a key and no associated data. Explain, in general, how to implement the class btElementType so it can contain both a key and data, and work correctly with the given implementation. 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Figure 11-22: Inheritance diagram for BinaryTree and BST 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Copyright  1997 Oxford University Press All Rights Reserved Code Example 11-12 // cx11-12.h // Code Example 11-12: Interface File: Binary Search Trees inheriting from // Binary Trees #ifndef __MB_CX11_12__ #define __MB_CX11_12__ #include "dslib.h" template < class btElementType > class BinaryTree { public: BinaryTree(); virtual bool isEmpty() const; // Precondition: None. // Postcondition: None. // Returns: true if and only if T is an empty tree 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Copyright  1997 Oxford University Press All Rights Reserved Code Example 11-12 virtual btElementType getData() const; // Precondition: !this->isEmpty() // Postcondition: None // Returns: The data associated with the root of the tree virtual void insert(const btElementType & d); // Precondition: none // Postconditions: this->getData() == d; !this->isEmpty() virtual BinaryTree * retrieve(const btElementType & d); // Postcondition: none // Returns: this // Note: A useless stub, will be redefined by child class virtual BinaryTree * left(); // Returns: (a pointer to) the left child of T 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Copyright  1997 Oxford University Press All Rights Reserved Code Example 11-12 virtual BinaryTree * right(); // Precondition: !this->isEmpty() // Postcondition: None // Returns: (a pointer to) the right child of T virtual void makeLeft(BinaryTree * T1); // Precondition: !this->isEmpty(); // this->left()->isEmpty() // Postcondition: this->left() == T1 virtual void makeRight(BinaryTree * T1); // this->right()->isEmpty() // Postcondition: this->right() == T1 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Copyright  1997 Oxford University Press All Rights Reserved Code Example 11-12 protected: bool nullTree; btElementType treeData; BinaryTree * leftTree; BinaryTree * rightTree; }; template < class btElementType > class BST : public BinaryTree < btElementType > { public: BST(); virtual void insert(const btElementType & d); // Precondition: if d is a left child, then d must be < parent->getData(); // if d is a right child, then d must be > parent->getData(); // Postconditions: T->retrieve(k)->getData() == d 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Copyright  1997 Oxford University Press All Rights Reserved Code Example 11-12 virtual BinaryTree < btElementType > * retrieve(const btElementType & d); // Precondition: none // Postcondition: none // Returns: if T contains a node matching d, then // T->retrieve(d)->getData() == d; otherwise, T->isEmpty() }; #endif 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Copyright  1997 Oxford University Press All Rights Reserved Code Example 11-13 // cx11-13.cpp // Code Example 11-13: Implementation File: Binary Tree #include "cx11-12.h" template < class btElementType > BinaryTree < btElementType > :: BinaryTree() { nullTree = true; leftTree = 0; rightTree = 0; } 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Copyright  1997 Oxford University Press All Rights Reserved Code Example 11-13 template < class btElementType > bool BinaryTree < btElementType > :: isEmpty() const { return nullTree; } btElementType BinaryTree < btElementType > :: getData() const assert(!isEmpty()); return treeData; 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Copyright  1997 Oxford University Press All Rights Reserved Code Example 11-13 template < class btElementType > void BinaryTree < btElementType > :: insert(const btElementType & d) { treeData = d; if (nullTree) { nullTree = false; leftTree = new BinaryTree; rightTree = new BinaryTree; } 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Copyright  1997 Oxford University Press All Rights Reserved Code Example 11-13 template < class btElementType > BinaryTree < btElementType > * BinaryTree < btElementType > :: retrieve(const btElementType & d) { return this; } BinaryTree < btElementType > :: left() assert(!isEmpty()); return leftTree; 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Copyright  1997 Oxford University Press All Rights Reserved Code Example 11-13 template < class btElementType > BinaryTree < btElementType > * BinaryTree < btElementType > :: right() { assert(!isEmpty()); return rightTree; } void BinaryTree < btElementType > :: makeLeft(BinaryTree * T1) assert(left()->isEmpty()); delete left(); leftTree = T1; 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Copyright  1997 Oxford University Press All Rights Reserved Code Example 11-13 template < class btElementType > void BinaryTree < btElementType > :: makeRight(BinaryTree * T1) { assert(!isEmpty()); assert(right()->isEmpty()); delete right(); rightTree = T1; } 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Copyright  1997 Oxford University Press All Rights Reserved Code Example 11-13 template < class btElementType > void BST < btElementType > :: insert(const btElementType & d) { if (nullTree) { nullTree = false; leftTree = new BST; rightTree = new BST; treeData = d; } else if (d == treeData) else if (d < treeData) leftTree->insert(d); else rightTree->insert(d); 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Copyright  1997 Oxford University Press All Rights Reserved Code Example 11-13 template < class btElementType > BinaryTree < btElementType > * BST < btElementType > :: retrieve(const btElementType & d) { if (nullTree || d == treeData) return this; else if (d < treeData) return leftTree->retrieve(d); else return rightTree->retrieve(d); } :: BST() : BinaryTree < btElementType >() 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Copyright  1997 Oxford University Press All Rights Reserved Exercises 11-18 The inheritance implementation in Code Example 11-12 and Code Example 11-13 has one unattractive feature: the makeLeft and makeRight functions are inherited by the BST, even though using these functions would allow the client to improperly destroy the structure of the BST. Explain 11-19 Since inheritance allows you to redefine how inherited member functions work, you can get around the problem described in Exercise 11-18, by redefining makeLeft and makeRight to do nothing. Rewrite the header and add implementations of makeLeft and makeRight that simply print out a warning to cerr and make no changes to the tree. 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Copyright  1997 Oxford University Press All Rights Reserved Exercises 11-20 Write a test driver for the BST that creates the tree in Figure 11-17 and traverses it in each of the three orders. 11-21 Experiment with the syntax for inheritance, using Code Example 11-12 and Code Example 11-13. For example, take the virtual keyword out of the base class and see what happens when you compile the code. 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Copyright  1997 Oxford University Press All Rights Reserved Exercise 11-22 You can use inheritance to create a class ExpressionTree derived from the base class BinaryTree. The ExpressionTree class should implement one new member function, evaluate, that returns the value obtained by evaluation the expression tree at the root. Show the class declaration for ExpressionTree 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Copyright  1997 Oxford University Press All Rights Reserved Algorithm 11-4 if the tree is not empty visit the root preOrderTraverse(left child) preOrderTraverse(right child) 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Figure 11-23: A tree that is expensive to process 5 6 8 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Figure 11-24: An efficient tree 14 6 20 3 9 18 25 1 4 7 12 16 19 22 27 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Figure 11-25: Shallowest trees for n=1, n=3, n=7, and n=15 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Copyright  1997 Oxford University Press All Rights Reserved Equation 11-1 f(d) = f(d - 1) + f(d - 1) + 1 = 2f(d - 1) + 1 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Copyright  1997 Oxford University Press All Rights Reserved Equation 11-2 f(0) = 1 f(1) = 3 f(2) = 7 f(3) = 15 f(4) = 31 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Copyright  1997 Oxford University Press All Rights Reserved Equation 11-3 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Copyright  1997 Oxford University Press All Rights Reserved Equation 11-4 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Copyright  1997 Oxford University Press All Rights Reserved Equation 11-5 hence: 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Copyright  1997 Oxford University Press All Rights Reserved Chapter Summary Tree represent data in a hierarchical manner. In a Binary Tree, each node has a left and a right child. Expression Trees are a Binary Tree that can represent arithmetic expressions. The data in a tree can be visited using in-order, pre-order, and post-order traversals. Function pointers can be used to pass one function to another as an argument. The Binary Search Tree is an ordered tree ADT. 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Copyright  1997 Oxford University Press All Rights Reserved Chapter Summary Binary Search Trees support efficient retrieval by key Inheritance can be used to model is-a relations. Inheritance can be implemented in C++ through base and derived classes. Inheritance supports code reuse. Binary Search Tree can have bad performance if they’re unbalanced, but very good performance when balanced. Treesort sorts a list using a Binary Search Tree. 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Programming Laboratory Problems 11-1 An ancestor tree lists the names of an individual’s ancestors. the root contains the name of a person (whom we’ll call the subject of the tree), the two nodes as the level 1 list the names of the subject's parents, the four nodes at level 2 list the subject’s grandparents and so forth. Write a program that reads in seven names, representing: (Continued on the next slide.) 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Programming Laboratory Problems subject subject’s mother subject’s father subject’s mother’s mother subject’s mother’s father subject’s father’s mother subject’s father’s father (Continued on the next slide.) 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Programming Laboratory Problems These items should be sorted in a Binary Tree, and then the program should answer queries of the form: name1 parent name2 or name1 grandparent name2 with either “yes” or “no” as appropriate. 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Programming Laboratory Problems 11-2 The Binary Tree ADT 11-1 on Page 273 doesn’t provide a way to get from a child to its parent. Define an operation, T.parent(), that returns the parent of a node, or 0 if that node is the root of the tree. Create a class, BinaryTree2Way, that inherits from BinaryTree, to implement the ADT with the parent operation. Test your derived class thoroughly. 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Programming Laboratory Problems 11-3 Write the following programs that analyze trees: int depth(const BinaryTree * btp) Precondition: None. Postcondition: None. Return: The depth of the BinaryTree rooted at btp. (Continued on the next slide.) 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Programming Laboratory Problems int degree(const BinaryTree * btp) Precondition: None. Postcondition: None. Return: The degree of the BinaryTree rooted at btp. I strongly recommend a recursive solution, which will make your program much simpler. If you write the program correctly it will work with BinaryTrees and BST’s without alteration. 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Programming Laboratory Problems 11-4 Design and implement a program that, given an pre-order and an in-order traversal of a tree, constructs the tree (or reports that the input is incorrect). See Exercise 11-10 on Page 291 for further discussion. 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Programming Laboratory Problems 11-5 The examples given for using BST’s all assume that the data is a single int. In many cases you want to store more complex data, e.g. an employee record. Implement a simple telephone number data base, in which each entry is an object with the following fields: first name, last name, telephone number. The items should be stored in the tree in alphabetical order by last name/first name. The “key” to making this work lies in overloading the < and = = operations on your object so that the ordering is correct. Note: you absolutely need not, and must not, modify the BST implementation to do this assignment. 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Programming Laboratory Problems 11-6 Using a BST, implement the Table ADT 10-1 on Page 243. Do not modify the BST code. 11-7 Write a program that reads in a description of a binary tree from a file and builds the tree. The file should consist of records in the form: A B C which indicates the A is the parent of B and C. 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

Programming Laboratory Problems 11-8 A forest is a set of zero or more trees. Design an ADT that will permit you to implement forests of binary tree, then implement it using the List ADT and the Binary Tree ADT. Be sure to test your implementation thoroughly. 11-9 Implement Treesort. Write a test driver that creates random sequences of ints, passes them to Treesort for sorting, and then tests to make sure that the sorting was correct. Use the Timer class3 to determine average performance of Treesort for lists of size 100 through 10000 by increments of 100, using 100 random lists at each point. Plot the time function using a spread sheet or other plotting software. How does the performance of Tree sort grow as function of n? 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved