CS 240Chapter 10 – TreesPage 177 10 Chapter 10 Trees The tree abstract data type provides a hierarchical to the representation of certain types of relationships.

Slides:



Advertisements
Similar presentations
DATA STRUCTURES USING C++ Chapter 5
Advertisements

Senem Kumova Metin Spring2009 BINARY TREES && TREE TRAVERSALS Chapter 10 in A Book on C.
CS 240Chapter 6 - StacksPage 21 Chapter 6 Stacks The stack abstract data type is essentially a list using the LIFO (last-in-first-out) policy for adding.
Chapter 6: Stacks STACK APPLICATIONS STACK IMPLEMENTATIONS CS
1 abstract containers hierarchical (1 to many) graph (many to many) first ith last sequence/linear (1 to 1) set.
1 Jake’s Pizza Shop Owner Jake Manager Chef Brad Carol Waitress Waiter Cook Helper Joyce Chris Max Len.
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.
CS 340Chapter 3: Lists, Stacks, and Queues1 Abstract Data Types An ADT is a set of operations upon a set of data. Implementation details are not specified.
trees1 Binary Trees trees2 Basic terminology nodesFinite set of nodes (may be empty -- 0 nodes), which contain data rootFirst node in tree is called.
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.
Starting Out with C++, 3 rd Edition 1 Chapter 20 Binary Trees.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 12 – Data Structures Outline 12.1Introduction.
1 abstract containers hierarchical (1 to many) graph (many to many) first ith last sequence/linear (1 to 1) set.
Data Structures Using C++ 2E Chapter 11 Binary Trees and B-Trees.
Marc Smith and Jim Ten Eyck
Binary Search Trees Chapter 6.
Data Structures Using C++1 Chapter 11 Binary Trees.
Trees Chapter 8. 2 Tree Terminology A tree consists of a collection of elements or nodes, organized hierarchically. The node at the top of a tree is called.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Templatized Tree.
1 TK1924 Program Design & Problem Solving Session 2011/2012 L8: Binary Trees.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 13: Pointers and Dynamic Data Structures Problem Solving, Abstraction,
Trees EENG212 Algorithms and Data Structures. Trees Outline  Introduction to Trees  Binary Trees: Basic Definitions  Traversing Binary Trees  Node.
Trees.ppt1 Introduction Many data structures are linear –unique first component –unique last component –other components have unique predecessor and successor.
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,
Lecture 10 Trees –Definiton of trees –Uses of trees –Operations on a tree.
Binary Trees Chapter Definition And Application Of Binary Trees Binary tree: a nonlinear linked list in which each node may point to 0, 1, or two.
Trees. Trees Traversal Inorder  (Left) Root (Right) Preorder  Root (Left) (Right) Postorder  (Left) (Right) Root Root LeftRight.
INTRODUCTION TO BINARY TREES P SORTING  Review of Linear Search: –again, begin with first element and search through list until finding element,
DATA STRUCTURES AND ALGORITHMS Lecture Notes 5 Prepared by İnanç TAHRALI.
Binary Trees 2 Overview Trees. Terminology. Traversal of Binary Trees. Expression Trees. Binary Search Trees.
A Binary Search Tree Binary Search Trees.
Prof. Amr Goneid, AUC1 Analysis & Design of Algorithms (CSCE 321) Prof. Amr Goneid Department of Computer Science, AUC Part R2. Binary Search Trees.
Pointers & Dynamic Data Structures Chapter Dynamic Data Structures t Arrays & structs are static (compile time) t Dynamic expand as program executes.
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 Chapter 8. 2 Tree Terminology A tree consists of a collection of elements or nodes, organized hierarchically. The node at the top of a tree is called.
 Trees Data Structures Trees Data Structures  Trees Trees  Binary Search Trees Binary Search Trees  Binary Tree Implementation Binary Tree Implementation.
Savitch - Chapters 9&11 CS Pointers A pointer holds the memory address of a variable. Main Memory Byte # Byte # Byte # Byte.
Review 1 Queue Operations on Queues A Dequeue Operation An Enqueue Operation Array Implementation Link list Implementation Examples.
Advance Data Structure 1 College Of Mathematic & Computer Sciences 1 Computer Sciences Department م. م علي عبد الكريم حبيب.
Data Structures Using Java1 Chapter 10 Binary Trees.
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.
Binary Search Tree. Tree  A nonlinear data structure consisting of nodes, each of which contains data and pointers to other nodes.  Each node has only.
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.
Copyright © 2012 Pearson Education, Inc. Chapter 20: Binary Trees.
Chapter 11 Binary Trees Dr. Youssef Harrath
Data Structures Using C++ 2E Chapter 11 Binary Trees.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 15. Dictionaries (1): A Key Table Class.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 20: Binary Trees.
1 Nell Dale Chapter 8 Binary Search Trees Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus C++ Plus Data Structures.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 20: Binary Trees.
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.
1 Trees 3: The Binary Search Tree Reading: Sections 4.3 and 4.6.
Binary Trees.
CSCE 210 Data Structures and Algorithms
CSCE 210 Data Structures and Algorithms
Chapter 12 – Data Structures
Data Structure and Algorithms
Data Structure #1: The Array
Binary Search Trees Chapter 7 Objectives
Binary Trees Lecture 36 Wed, Apr 21, /21/2018 Binary Trees.
Chapter 20: Binary Trees.
Chapter 7 TREES.
Data Structures Using Java
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.
Chapter 16-2 Linked Structures
Trees 3: The Binary Search Tree
Chapter 21: Binary Trees.
Pointers & Dynamic Data Structures
Chapter 20: Binary Trees.
Presentation transcript:

CS 240Chapter 10 – TreesPage Chapter 10 Trees The tree abstract data type provides a hierarchical to the representation of certain types of relationships. The tree abstract data type provides a hierarchical structure to the representation of certain types of relationships. Array Implementation Array Implementation Applications Applications Linked List Implementation Linked List Implementation General Trees General Trees Binary Search Trees Binary Search Trees

CS 240Chapter 10 – TreesPage 178 The Binary Tree ADT The binary tree abstract data type is a structure in which entries are configured to have at most two offspring. Root Leaf Node Leaf Binary Tree In addition to constructors and a destructor, the binary tree ADT needs the following functions: isEmpty - to determine whether the binary tree contains any entries insert - to insert a new entry at the appropriate location within the tree traverse - some mechanism to explore the tree The binary aspect of this structure makes it particularly useful in applications where individual choices are needed, making it possible to recursively proceed to the right offspring or to the left offspring of the current node. For example, video games frequently present a player with two options, using a game tree to keep track of the alternatives selected by the player.

CS 240Chapter 10 – TreesPage 179 Basic Binary Tree Terminology value leaf nodes sibling nodes parent node child node

CS 240Chapter 10 – TreesPage 180 Application: The Heap Keeps the data in each node greater than or equal to the data in both of its subtrees.

CS 240Chapter 10 – TreesPage 181 Application: The Binary Search Tree Keeps the data in each node's left subtree less than or equal to the node's data, and the data in the node's right subtree greater than or equal to the node's data

CS 240Chapter 10 – TreesPage 182 Application: The Binary Expression Tree Strategically places the binary operators in the upper nodes, and the primitive operands in the leaf nodes. Example: (A+B)/C+D*((E+F)%(G-H))++//** ++CCDD ++AA % EEGGFFHH --BB

CS 240Chapter 10 – TreesPage 183 Array Implementation Of Binary Tree  Place root in slot #0  Place left child of slot k's node in slot #(2*k+1)  Place right child of slot k's node in slot #(2*k+2)  Locate parent of slot k's node in slot #((k-1)/2)                 

CS 240Chapter 10 – TreesPage 184 Array Implementation Of Binary Tree // Class declaration file: bintree.h // // This file contains the array implementation of the binary tree ADT. // #include using namespace std; #ifndef BIN_TREE_H // DECLARATION SECTION FOR THE BINARY TREE CLASS TEMPLATE const int MAX_TREE_NODES = 15; template class binary_tree { public: // Class constructors binary_tree(); binary_tree(const binary_tree &bt); // Member functions bool isEmpty(); void insert(const E &item); void preorder_traverse(int location); void inorder_traverse(int location); void postorder_traverse(int location); binary_tree & operator = (const binary_tree &bt); void display_array(); // Class declaration file: bintree.h // // This file contains the array implementation of the binary tree ADT. // #include using namespace std; #ifndef BIN_TREE_H // DECLARATION SECTION FOR THE BINARY TREE CLASS TEMPLATE const int MAX_TREE_NODES = 15; template class binary_tree { public: // Class constructors binary_tree(); binary_tree(const binary_tree &bt); // Member functions bool isEmpty(); void insert(const E &item); void preorder_traverse(int location); void inorder_traverse(int location); void postorder_traverse(int location); binary_tree & operator = (const binary_tree &bt); void display_array();

CS 240Chapter 10 – TreesPage 185 protected: // Data members struct node// The node structure is {// set up so that if the bool vacant;// vacant field is FALSE, E data;// then the data field is };// irrelevant. node tree[MAX_TREE_NODES];// Array of nodes int number_nodes;// Number of nodes in tree // Member function void insertStartingHere(const E &item, int location); }; // IMPLEMENTATION SECTION FOR THE BINARY TREE CLASS TEMPLATE ////////////////////////// // Default constructor. // ////////////////////////// template binary_tree ::binary_tree() { number_nodes = 0; for (int i = 0; i < MAX_TREE_NODES; i++) tree[i].vacant = true; } protected: // Data members struct node// The node structure is {// set up so that if the bool vacant;// vacant field is FALSE, E data;// then the data field is };// irrelevant. node tree[MAX_TREE_NODES];// Array of nodes int number_nodes;// Number of nodes in tree // Member function void insertStartingHere(const E &item, int location); }; // IMPLEMENTATION SECTION FOR THE BINARY TREE CLASS TEMPLATE ////////////////////////// // Default constructor. // ////////////////////////// template binary_tree ::binary_tree() { number_nodes = 0; for (int i = 0; i < MAX_TREE_NODES; i++) tree[i].vacant = true; }

CS 240Chapter 10 – TreesPage 186 // Copy constructor. // template binary_tree ::binary_tree(const binary_tree &bt) { number_nodes = bt.number_nodes; for (int i = 0; i < MAX_TREE_NODES; i++) if (bt.tree[i].vacant) tree[i].vacant = true; else tree[i] = bt.tree[i]; } // Assignment operator. // template binary_tree & binary_tree ::operator = (const binary_tree &bt) { number_nodes = bt.number_nodes; for (int i = 0; i < MAX_TREE_NODES; i++) if (bt.tree[i].vacant) tree[i].vacant = true; else tree[i] = bt.tree[i]; return *this; } // Copy constructor. // template binary_tree ::binary_tree(const binary_tree &bt) { number_nodes = bt.number_nodes; for (int i = 0; i < MAX_TREE_NODES; i++) if (bt.tree[i].vacant) tree[i].vacant = true; else tree[i] = bt.tree[i]; } // Assignment operator. // template binary_tree & binary_tree ::operator = (const binary_tree &bt) { number_nodes = bt.number_nodes; for (int i = 0; i < MAX_TREE_NODES; i++) if (bt.tree[i].vacant) tree[i].vacant = true; else tree[i] = bt.tree[i]; return *this; }

CS 240Chapter 10 – TreesPage 187 // Empty function. // template bool binary_tree ::isEmpty() { return (number_nodes == 0); } // Insert function; inserts via insertStartingHere function. // template void binary_tree ::insert(const E &item) { assert(number_nodes < MAX_TREE_NODES); // Room in tree? insertStartingHere(item, 0); number_nodes++; } // Preorder_traverse function; prints tree contents in preorder. // template void binary_tree ::preorder_traverse(int location) { if ((location < MAX_TREE_NODES) && (!tree[location].vacant)) { cout << tree[location].data << '\t'; preorder_traverse(2 * location + 1); preorder_traverse(2 * location + 2); } return; } // Empty function. // template bool binary_tree ::isEmpty() { return (number_nodes == 0); } // Insert function; inserts via insertStartingHere function. // template void binary_tree ::insert(const E &item) { assert(number_nodes < MAX_TREE_NODES); // Room in tree? insertStartingHere(item, 0); number_nodes++; } // Preorder_traverse function; prints tree contents in preorder. // template void binary_tree ::preorder_traverse(int location) { if ((location < MAX_TREE_NODES) && (!tree[location].vacant)) { cout << tree[location].data << '\t'; preorder_traverse(2 * location + 1); preorder_traverse(2 * location + 2); } return; }

CS 240Chapter 10 – TreesPage 188 ///////////////////////////////////////////////////////////////// // Inorder_traverse function; prints tree contents in inorder. // ///////////////////////////////////////////////////////////////// template void binary_tree ::inorder_traverse(int location) { if ((location < MAX_TREE_NODES) && (!tree[location].vacant)) { inorder_traverse(2 * location + 1); cout << tree[location].data << '\t'; inorder_traverse(2 * location + 2); } return; } ///////////////////////////////////////////////////////////////////// // Postorder_traverse function; prints tree contents in postorder. // ///////////////////////////////////////////////////////////////////// template void binary_tree ::postorder_traverse(int location) { if ((location < MAX_TREE_NODES) && (!tree[location].vacant)) { postorder_traverse(2 * location + 1); postorder_traverse(2 * location + 2); cout << tree[location].data << '\t'; } return; } ///////////////////////////////////////////////////////////////// // Inorder_traverse function; prints tree contents in inorder. // ///////////////////////////////////////////////////////////////// template void binary_tree ::inorder_traverse(int location) { if ((location < MAX_TREE_NODES) && (!tree[location].vacant)) { inorder_traverse(2 * location + 1); cout << tree[location].data << '\t'; inorder_traverse(2 * location + 2); } return; } ///////////////////////////////////////////////////////////////////// // Postorder_traverse function; prints tree contents in postorder. // ///////////////////////////////////////////////////////////////////// template void binary_tree ::postorder_traverse(int location) { if ((location < MAX_TREE_NODES) && (!tree[location].vacant)) { postorder_traverse(2 * location + 1); postorder_traverse(2 * location + 2); cout << tree[location].data << '\t'; } return; }

CS 240Chapter 10 – TreesPage 189 // Display_array function; prints tree contents as an // // array, printing the word vacant if a node is vacant. // template void binary_tree ::display_array() { int index; for (int i = 0; i < MAX_TREE_NODES/5; i++) { for (int j = 0; j < 5; j++) { index = (MAX_TREE_NODES/5)*j+i; cout << setw(2) << index << " = "; if (tree[index].vacant) cout << setw(6) << "vacant" << setw(3) << ""; else cout << setw(6) << tree[index].data << setw(3) << ""; } cout << endl; } // Display_array function; prints tree contents as an // // array, printing the word vacant if a node is vacant. // template void binary_tree ::display_array() { int index; for (int i = 0; i < MAX_TREE_NODES/5; i++) { for (int j = 0; j < 5; j++) { index = (MAX_TREE_NODES/5)*j+i; cout << setw(2) << index << " = "; if (tree[index].vacant) cout << setw(6) << "vacant" << setw(3) << ""; else cout << setw(6) << tree[index].data << setw(3) << ""; } cout << endl; }

CS 240Chapter 10 – TreesPage 190 /////////////////////////////////////////////////////////////// // InsertStartingHere function; inserts item into tree using // // ordering (i.e., inserting smaller values to the left and // // larger values to the right). // /////////////////////////////////////////////////////////////// template void binary_tree ::insertStartingHere(const E &item, int location) { assert(location < MAX_TREE_NODES); // Must be legitimate // array index if (tree[location].vacant) { tree[location].data = item; tree[location].vacant = false; } else if (item < tree[location].data) insertStartingHere(item, 2 * location + 1); else insertStartingHere(item, 2 * location + 2); } #define BIN_TREE_H #endif /////////////////////////////////////////////////////////////// // InsertStartingHere function; inserts item into tree using // // ordering (i.e., inserting smaller values to the left and // // larger values to the right). // /////////////////////////////////////////////////////////////// template void binary_tree ::insertStartingHere(const E &item, int location) { assert(location < MAX_TREE_NODES); // Must be legitimate // array index if (tree[location].vacant) { tree[location].data = item; tree[location].vacant = false; } else if (item < tree[location].data) insertStartingHere(item, 2 * location + 1); else insertStartingHere(item, 2 * location + 2); } #define BIN_TREE_H #endif

CS 240Chapter 10 – TreesPage 191 Example Driver For The Array Implementation // Program file: treedriv.cpp // // This program illustrates the // // creation of a binary tree. // #include #include "bintree.h" using namespace std; void print_tree(binary_tree &tree); // The main function queries the // // user for new tree elements. // void main() { binary_tree tree; int number; cout << "Enter a number: "; cin >> number; while (number > 0) { tree.insert(number); tree.display_array(); cout << "Enter a number: "; cin >> number; } // Program file: treedriv.cpp // // This program illustrates the // // creation of a binary tree. // #include #include "bintree.h" using namespace std; void print_tree(binary_tree &tree); // The main function queries the // // user for new tree elements. // void main() { binary_tree tree; int number; cout << "Enter a number: "; cin >> number; while (number > 0) { tree.insert(number); tree.display_array(); cout << "Enter a number: "; cin >> number; } print_tree(tree); } // The print_tree function outputs // // the final contents of the tree, // // first by displaying the entire // // array, then by printing out the // // non-vacant tree elements in in- // // order, preorder, and postorder. // void print_tree(binary_tree &tree) { cout << "Array contents: \n"; tree.display_array(); cout << “\nInorder traversal: \n"; tree.inorder_traverse(0); cout << “\nPreorder traversal: \n"; tree.preorder_traverse(0); cout << “\nPostorder traversal: \n"; tree.postorder_traverse(0); cout << endl << endl; } print_tree(tree); } // The print_tree function outputs // // the final contents of the tree, // // first by displaying the entire // // array, then by printing out the // // non-vacant tree elements in in- // // order, preorder, and postorder. // void print_tree(binary_tree &tree) { cout << "Array contents: \n"; tree.display_array(); cout << “\nInorder traversal: \n"; tree.inorder_traverse(0); cout << “\nPreorder traversal: \n"; tree.preorder_traverse(0); cout << “\nPostorder traversal: \n"; tree.postorder_traverse(0); cout << endl << endl; }

CS 240Chapter 10 – TreesPage 192

CS 240Chapter 10 – TreesPage 193 A Good Use For The Array Implementation: Heaps // Class declaration file: heap.h // // This file contains the array implementation of the heap ADT. // #include "bintree.h" #include using namespace std; #ifndef HEAP_H // DECLARATION SECTION FOR THE HEAP CLASS TEMPLATE template class heap: public binary_tree { public: // Class constructors heap(); heap(const heap &h); // Member functions void insert(const E &item); heap & operator = (const heap &h); };

CS 240Chapter 10 – TreesPage 194 // IMPLEMENTATION SECTION FOR // THE HEAP CLASS TEMPLATE ////////////////////////// // Default constructor. // ////////////////////////// template heap ::heap(): binary_tree () { } /////////////////////// // Copy constructor. // /////////////////////// template heap ::heap(const heap &h) { number_nodes = h.number_nodes; for (int i=0; i<MAX_TREE_NODES; ++i) { if (h.tree[i].vacant) tree[i].vacant = true; else tree[i] = h.tree[i]; } ////////////////////////// // Assignment operator. // ////////////////////////// template heap & heap ::operator = (const heap &h) { number_nodes = h.number_nodes; for (int i=0; i<MAX_TREE_NODES; ++i) { if (h.tree[i].vacant) tree[i].vacant = true; else tree[i] = h.tree[i]; } return *this; }

CS 240Chapter 10 – TreesPage 195 ///////////////////////////////////////////////////////////////////////// // Insert function; inserts into the heap to retain the heap structure // // and to ensure non-fragmentation of the array structure, moving low // // elements down when a high element is inserted. // ///////////////////////////////////////////////////////////////////////// template void heap ::insert(const E &item) { int location, parent; assert(number_nodes < MAX_TREE_NODES); // Now walk the new item up the tree, starting at location location = number_nodes; parent = (location-1) / 2; while ((location > 0) && (tree[parent].data < item)) { tree[location] = tree[parent]; location = parent; parent = (location-1) / 2; } tree[location].data = item; tree[location].vacant = false; number_nodes++; } #define HEAP_H #endif

CS 240Chapter 10 – TreesPage 196 Example Driver For The Heap Implementation // Program file: heapdriv.cpp // // This program illustrates // // the creation of a heap. // #include #include "heap.h" using namespace std; void print_heap(heap &tree); // The main function queries the // // user for new heap elements. // void main() { heap tree; int number; cout << "Enter a number: "; cin >> number; while (number > 0) { tree.insert(number); tree.display_array(); cout << "Enter a number: "; cin >> number; } print_heap(tree); } // The print_heap function outputs // // the final contents of the heap, // // first by displaying the entire // // array, then by printing out the // // non-vacant heap elements in in- // // order, preorder, and postorder. // void print_heap(heap &tree) { cout << "Array contents: \n"; tree.display_array(); cout << "\nInorder traversal: \n"; tree.inorder_traverse(0); cout << " \nPreorder traversal: \n"; tree.preorder_traverse(0); cout << " \nPostorder traversal: n"; tree.postorder_traverse(0); cout << endl << endl; }

CS 240Chapter 10 – TreesPage 197

CS 240Chapter 10 – TreesPage 198 Linked List Implementation Of Binary Tree // Class declaration file: bintree.h // This file contains the array implementation of the binary tree ADT. // #ifndef BIN_TREE_H #include using namespace std; // DECLARATION SECTION FOR LINKED VERSION OF BINARY TREE template class binary_tree { public: // Class constructors and destructor binary_tree(); binary_tree(const binary_tree &bt); ~binary_tree(); // Member functions bool isEmpty() const; void insert(const E &item); void preorderTraverse(ofstream &os) const; void inorderTraverse(ofstream &os) const; void postorderTraverse(ofstream &os) const; binary_tree & operator = (const binary_tree &bt);

CS 240Chapter 10 – TreesPage 199 protected: // Data members struct node; typedef node* node_ptr; struct node { E data; node_ptr left; node_ptr right; }; node_ptr root; // Member functions node_ptr get_node(const E &data); void insertIntoTree(node_ptr &treeRoot, const E &data); void copyTree(node_ptr treeRoot) const; void destroyTree(node_ptr treeRoot); void preorderOutput(node_ptr treeRoot, ofstream &os) const; void inorderOutput(node_ptr treeRoot, ofstream &os) const; void postorderOutput(node_ptr treeRoot, ofstream &os) const; };

CS 240Chapter 10 – TreesPage 200 // IMPLEMENTATION SECTION FOR LINKED VERSION OF BINARY TREE // Default constructor. // template binary_tree ::binary_tree() { root = NULL; } // Copy constructor. // template binary_tree ::binary_tree(const binary_tree &bt) { root = NULL; copyTree(bt.root); } // Assignment operator. // template binary_tree & binary_tree ::operator = (const binary_tree &bt) { root = NULL; copyTree(bt.root); return *this; }

CS 240Chapter 10 – TreesPage 201 // Function copyTree: Starting at the node pointed to by // // parameter treeRoot, this function recursively copies the // // elements of an existing tree into the *this tree. By // // proceeding in a preorder fashion, this function ensures // // that the elements of *this will correspond exactly (in // // value and position) to the elements of the existing tree. // template void binary_tree ::copyTree(node_ptr treeRoot) const { if (treeRoot != NULL) { insert(treeRoot->data); copyTree(treeRoot->left); copyTree(treeRoot->right); } // Destructor. // template binary_tree ::~binary_tree() { destroyTree(root); root = NULL; }

CS 240Chapter 10 – TreesPage 202 // Function destroyTree: returns all memory associated with // // the tree to the system heap, by recursively destroying // // the two subtrees and then deleting the root. // template void binary_tree ::destroyTree(node_ptr treeRoot) { if (treeRoot != NULL) { destroyTree(treeRoot->left); destroyTree(treeRoot->right); delete treeRoot; } // Empty function. // template bool binary_tree ::isEmpty() const { return root == NULL; }

CS 240Chapter 10 – TreesPage 203 // Insert function. // template void binary_tree ::insert(const E &item) { insertIntoTree(root, item); } // Function insertIntoTree: recursively inserts parameter // // item into tree using binary search tree assumption. // template void binary_tree ::insertIntoTree(node_ptr &treeRoot, const E &item) { if (treeRoot == NULL) treeRoot = get_node(item); else if (item data) insertIntoTree(treeRoot->left, item); else insertIntoTree(treeRoot->right, item); }

CS 240Chapter 10 – TreesPage 204 // Function preorderTraverse. // template void binary_tree ::preorderTraverse(ofstream &os) const { preorderOutput(root, os); } // Function preorderOutput: Outputs contents of // // the tree into parameterized file by recursively // // traversing the tree in preorder. // template void binary_tree ::preorderOutput(node_ptr treeRoot, ofstream &os) const { if (treeRoot != NULL) { os data << endl; preorderOutput(treeRoot->left, os); preorderOutput(treeRoot->right, os); }

CS 240Chapter 10 – TreesPage 205 // Function inorderTraverse. // template void binary_tree ::inorderTraverse(ofstream &os) const { inorderOutput(root, os); } // Function inorderOutput: Outputs contents of // // the tree into parameterized file by recursively // // traversing the tree in inorder. // template void binary_tree ::inorderOutput(node_ptr treeRoot, ofstream &os) const { if (treeRoot != NULL) { inorderOutput(treeRoot->left, os); os data << endl; inorderOutput(treeRoot->right, os); }

CS 240Chapter 10 – TreesPage 206 // Function postorderTraverse. // template void binary_tree ::postorderTraverse(ofstream &os) const { postorderOutput(root, os); } // Function postorderOutput: Outputs contents of // // the tree into parameterized file by recursively // // traversing the tree in postorder. // template void binary_tree ::postorderOutput(node_ptr treeRoot, ofstream &os) const { if (treeRoot != NULL) { postorderOutput(treeRoot->left, os); postorderOutput(treeRoot->right, os); os data << endl; }

CS 240Chapter 10 – TreesPage 207 // Function get_node: Dynamically allocates space for a new // // tree node, placing the parameter item's value into the // // new node, and initializing both of its pointers to NULL. // template typename binary_tree ::node_ptr binary_tree ::get_node(const E &item) { node_ptr temp = new node; assert(temp != NULL); temp->data = item; temp->left = NULL; temp->right = NULL; return temp; } #define BIN_TREE_H #endif

CS 240Chapter 10 – TreesPage 208 Example Driver For The Linked List Implementation // Program file: testtree.cpp // This program illustrates working // with a binary tree. The input // consists of an unordered list of // integers from a file. The // output consists of three files // containing the preorder, inorder, // and postorder traversals of the // binary search tree that is con- // structed from the input integers. #include #include "bintree.h" using namespace std; void main() { int number; ifstream input_file; ofstream pre_file; ofstream in_file; ofstream post_file; binary_tree tree; input_file.open("numbers.txt"); pre_file.open("preordered.txt"); in_file.open("inordered.txt"); post_file.open("postordered.txt"); input_file >> number; while (!input_file.eof()) { tree.insert(number); input_file >> number; } input_file.close(); tree.preorderTraverse(pre_file); tree.inorderTraverse(in_file); tree.postorderTraverse(post_file); pre_file.close(); in_file.close(); post_file.close(); return; }

CS 240Chapter 10 – TreesPage 209 File Contents numbers.txt preordered.txt inordered.txt postordered.txt

CS 240Chapter 10 – TreesPage 210 New Recursive Traversal Member Function // Kick off the recursion to count the binary tree’s pairs of “twins” // (i.e., the number of offspring pairs with identical values). template int binary_tree ::twinTraverse() { return twinCount(root); } // Recursive member function to determine the number of twin offspring // pairs, starting with the subtree rooted at the parameter treeRoot. template int binary_tree ::twinCount(node_ptr treeRoot) { if (treeRoot == NULL) return 0; else if ((treeRoot->left != NULL) && (treeRoot->right != NULL) && (treeRoot->left->data == treeRoot->right->data)) return (1 + twinCount(treeRoot->left) + twinCount(treeRoot->right)); else return (twinCount(treeRoot->left) + twinCount(treeRoot->right)); }

CS 240Chapter 10 – TreesPage General Trees What about non-binary trees? Application Example: Game Trees

CS 240Chapter 10 – TreesPage 212 How would general trees be implemented? Common approach: Use binary trees, with offspring and sibling pointers A A D D F F I I N N M M L L K K E E J J B B C C H H G G A A D D F F I I N N M M L L K K E E J J B B C C H H G G Actual tree Binary representation, with left pointers for “first offspring” and right pointers for “next sibling” Binary representation, with left pointers for “first offspring” and right pointers for “next sibling”