Presentation is loading. Please wait.

Presentation is loading. Please wait.

Copyright  1997 Oxford University Press All Rights Reserved

Similar presentations


Presentation on theme: "Copyright  1997 Oxford University Press All Rights Reserved"— Presentation transcript:

1 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

2 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

3 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

4 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

5 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

6 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

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

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

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

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

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

12 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 / * 3 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

13 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

14 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

15 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

16 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

17 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

18 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

19 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

20 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

21 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

22 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

23 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

24 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

25 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

26 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

27 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

28 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

29 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

30 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

31 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

32 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

33 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

34 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

35 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

36 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

37 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

38 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

39 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

40 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

41 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

42 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

43 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 / * 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

44 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

45 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

46 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

47 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

48 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

49 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

50 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

51 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

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

53 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

54 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

55 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

56 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

57 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

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

59 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

60 Copyright  1997 Oxford University Press All Rights Reserved
Exercise 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: in-order: (Hint: You know that 3 is the head (why?), so the nodes 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

61 Copyright  1997 Oxford University Press All Rights Reserved
Exercise 11-10 For the following expression: 17 * (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

62 Copyright  1997 Oxford University Press All Rights Reserved
Exercises 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. Add a function postOrderTraversal to Code Example 11-7 on Page Write a driver to test your function for correct operation. 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

63 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

64 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

65 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

66 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

67 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

68 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

69 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

70 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

71 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

72 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

73 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

74 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

75 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

76 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

77 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

78 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

79 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

80 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

81 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

82 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

83 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

84 Copyright  1997 Oxford University Press All Rights Reserved
Exercises Trace the process of inserting the following items into the BST on Figure on Page 295, and draw the resulting tree: 21, 30, 50, 34 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

85 Copyright  1997 Oxford University Press All Rights Reserved
Exercises Give a possible order that items might have been inserted to create the tree in Figure on Page 293. 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

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

87 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

88 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

89 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

90 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

91 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

92 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

93 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

94 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

95 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

96 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

97 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

98 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

99 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

100 Copyright  1997 Oxford University Press All Rights Reserved
Exercises The inheritance implementation in Code Example and Code Example 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 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

101 Copyright  1997 Oxford University Press All Rights Reserved
Exercises Write a test driver for the BST that creates the tree in Figure and traverses it in each of the three orders. Experiment with the syntax for inheritance, using Code Example and Code Example 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

102 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

103 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

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

105 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

106 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

107 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

108 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

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

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

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

112 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

113 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

114 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

115 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

116 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

117 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

118 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

119 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

120 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 on Page 291 for further discussion. 5/31/2019 Copyright  1997 Oxford University Press All Rights Reserved

121 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

122 Programming Laboratory Problems
11-6 Using a BST, implement the Table ADT 10-1 on Page 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

123 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 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


Download ppt "Copyright  1997 Oxford University Press All Rights Reserved"

Similar presentations


Ads by Google