Starting Out with C++, 3 rd Edition 1 Chapter 20 Binary Trees.

Slides:



Advertisements
Similar presentations
Chapter 17 Linked Lists.
Advertisements

Senem Kumova Metin Spring2009 BINARY TREES && TREE TRAVERSALS Chapter 10 in A Book on C.
Main Index Contents 11 Main Index Contents Tree StructuresTree Structures (3 slides) Tree Structures Tree Node Level and Path Len. Tree Node Level and.
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.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 19 Binary.
Data Structures Using C++ 2E Chapter 11 Binary Trees and B-Trees.
CS21, Tia Newhall Binary Search Trees (BST) 1.Hierarchical data structure with a single pointer to root node 2.Each node has at most two child nodes (a.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 19: Binary Trees.
C++ Programming: Program Design Including Data Structures, Third Edition Chapter 20: Binary Trees.
Binary Search Trees Chapter 7 Objectives
By : Budi Arifitama Pertemuan ke Objectives Upon completion you will be able to: Create and implement binary search trees Understand the operation.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Data Structures Trees.
Review Binary Tree Binary Tree Representation Array Representation Link List Representation Operations on Binary Trees Traversing Binary Trees Pre-Order.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Templatized Tree.
Chapter 19: Binary Trees. Objectives In this chapter, you will: – Learn about binary trees – Explore various binary tree traversal algorithms – Organize.
1 TK1924 Program Design & Problem Solving Session 2011/2012 L8: Binary Trees.
Trees EENG212 Algorithms and Data Structures. Trees Outline  Introduction to Trees  Binary Trees: Basic Definitions  Traversing Binary Trees  Node.
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,
Binary Trees 2 Overview Trees. Terminology. Traversal of Binary Trees. Expression Trees. Binary Search Trees.
Tree (new ADT) Terminology:  A tree is a collection of elements (nodes)  Each node may have 0 or more successors (called children)  How many does a.
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 Data Structures Trees Data Structures  Trees Trees  Binary Search Trees Binary Search Trees  Binary Tree Implementation Binary Tree Implementation.
Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Modified for use at Midwestern State University Chapter.
Topics Definition and Application of Binary Trees Binary Search Tree Operations.
1 Chapter 7 Objectives Upon completion you will be able to: Create and implement binary search trees Understand the operation of the binary search tree.
1 CSE 2341 Object Oriented Programming with C++ Note Set #21.
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.
Binary Search Trees (BST)
Trees Namiq Sultan. Trees Trees are very flexible, versatile and powerful non-liner data structure that can be used to represent data items possessing.
Trees Chapter 10. CS 308 2Chapter Trees Preview: Preview: The data organizations presented in previous chapters are linear, in that items are one.
Data Structures and Algorithms Introduction to Binary and Binary Search Trees Prepared by: S. Kondakci.
Copyright © 2012 Pearson Education, Inc. Chapter 20: Binary Trees.
Data Structures Using C++ 2E Chapter 11 Binary Trees.
Concepts of Algorithms CSC-244 Unit 19 & 20 Binary Search Tree (BST) Shahid Iqbal Lone Computer College Qassim University K.S.A.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 20: Binary Trees.
CMSC 202, Version 5/02 1 Trees. CMSC 202, Version 5/02 2 Tree Basics 1.A tree is a set of nodes. 2.A tree may be empty (i.e., contain no nodes). 3.If.
1 CSC 211 Data Structures Lecture 11 Dr. Iftikhar Azim Niaz 1.
1 Linked List. Outline Introduction Insertion Description Deletion Description Basic Node Implementation Conclusion.
CS 240Chapter 10 – TreesPage Chapter 10 Trees The tree abstract data type provides a hierarchical to the representation of certain types of relationships.
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.
Binary Search Trees. 2 Overview Recursive linked list ops Binary Trees.
Binary Search Trees Manolis Koubarakis Data Structures and Programming Techniques 1.
Binary Search Trees Chapter 7 Objectives
Chapter 12 – Data Structures
Definition and Application of Binary Trees
Data Structure and Algorithms
Pointers and Linked Lists
Recursive Objects (Part 4)
List ADT & Linked Lists.
Binary Search Trees Chapter 7 Objectives
Binary Search Tree (BST)
CMSC 341 Introduction to Trees.
Data Structures Using C++ 2E
Chapter 20: Binary 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.
Chapter 21: Binary Trees.
Find in a linked list? first last 7  4  3  8 NULL
Tree A tree is a data structure in which each node is comprised of some data as well as node pointers to child nodes
Prepared by: S. Kondakci
Chapter 10 1 – Binary Trees Tree Structures (3 slides)
Trees Chapter 10.
Pointers & Dynamic Data Structures
Chapter 20: Binary Trees.
Data Structures Using C++ 2E
Presentation transcript:

Starting Out with C++, 3 rd Edition 1 Chapter 20 Binary Trees

Starting Out with C++, 3 rd Edition Definition and Applications of Binary Trees A binary tree is a non-linear linked list where each node may point to two other nodes.

Starting Out with C++, 3 rd Edition 3 Definition and Applications of Binary Trees It is anchored at the top by a tree pointer, which is like the head pointer in a linked list. The first node in the list is called the root node. The root node has pointers to two other nodes, which are called children, or child nodes.

Starting Out with C++, 3 rd Edition 4 Definition and Applications of Binary Trees A node that has no children is called a leaf node. All pointers that do not point to a node are set to NULL.

Starting Out with C++, 3 rd Edition 5 Definition and Applications of Binary Trees Binary trees can be divided into subtrees. A subtree is an entire branch of the tree, from one particular node down.

Starting Out with C++, 3 rd Edition 6 Definition and Applications of Binary Trees Binary trees are excellent data structures for searching large amounts of information. They are commonly used in database applications to organize key values that index database records. When used to facilitate searches, a binary tree is called a binary search tree.

Starting Out with C++, 3 rd Edition 7 Definition and Applications of Binary Trees Information is stored in binary search trees in a way that makes a binary search simple. For example, look at Figure Values are stored in a binary tree so that a node's left child holds data whose value is less than the node's data, and the node's right child holds data whose value is greater tan the node's data.

Starting Out with C++, 3 rd Edition 8 Definition and Applications of Binary Trees It is also true that all the nodes to the left of a node hold values less than the node's value. Likewise, all the nodes to the right of a node hold values that are greater than the node's data. When an application is searching a binary tree, it starts at the root node. If the root node does not hold the search value, the application branches either to the left or right child, depending on whether the search value is less than or grater than the value at the root node.

Starting Out with C++, 3 rd Edition 9 Definition and Applications of Binary Trees This process continues until the value is found. Figure 20-4 illustrates the search pattern for finding the value P in the binary tree.

Starting Out with C++, 3 rd Edition Binary Search Tree Operations Creating a Node: We will demonstrate binary tree operations using the IntBinaryTree class. The basis of our binary tree node is the following struct declaration: struct TreeNode { int value; TreeNode *left; TreeNode *right; }; The struct is implemented in the class shown next…

Starting Out with C++, 3 rd Edition 11 IntBinaryTree.h class IntBinaryTree { public: struct TreeNode { int value; TreeNode *left; TreeNode *right; }; TreeNode *root; void destroySubTree(TreeNode *); void deleteNode(int, TreeNode *&); void makeDeletion(TreeNode *&); void displayInOrder(TreeNode *); void displayPreOrder(TreeNode *); void displayPostOrder(TreeNode *);

Starting Out with C++, 3 rd Edition 12 IntBinaryTree.h (continued) public: IntBinaryTree()// Constructor { root = NULL; } ~IntBinaryTree()// Destructor { destroySubTree(root); } void insertNode(int); bool searchNode(int); void remove(int); void showNodesInOrder(void) {displayInOrder(root); } void showNodesPreOrder() {displayPreOrder(root); } void showNodesPostOrder() {displayPostOrder(root); } };

Starting Out with C++, 3 rd Edition Binary Search Tree Operations Inserting a Node:First, a new node is allocated and its value member is initialized with the new value. The left and right child pointers are set to NULL, because all nodes must be inserted as leaf nodes. Next, we determine if the tree is empty. If so, we simply make root point to it, and there is nothing else to be done. But, if there are nodes in the tree, we must find the new node's proper insertion point.

Starting Out with C++, 3 rd Edition Binary Search Tree Operations If the new value is less than the root node's value, we know it will be inserted somewhere in the left subtree. Otherwise, the value will be inserted into the right subtree. We simply traverse the subtree, comparing each node along the way with the new node's value, and deciding if we should continue to the left or the right. When we reach a child pointer that is set to NULL, we have found out insertion point.

Starting Out with C++, 3 rd Edition 15 The insertNode Member Function void IntBinaryTree::insertNode(int num) { TreeNode *newNode,// Pointer to a new node *nodePtr;// Pointer to traverse the tree // Create a new node newNode = new TreeNode; newNode->value = num; newNode->left = newNode->right = NULL; if (!root)// Is the tree empty? root = newNode; else { nodePtr = root;

Starting Out with C++, 3 rd Edition 16 The insertNode Member Function while (nodePtr != NULL) { if (num value) { if (nodePtr->left) nodePtr = nodePtr->left; else { nodePtr->left = newNode; break; } }

Starting Out with C++, 3 rd Edition 17 The insertNode Member Function else if (num > nodePtr->value) { if (nodePtr->right) nodePtr = nodePtr->right; else { nodePtr->right = newNode; break; } } else { cout << "Duplicate value found in tree.\n"; break; } } } }

Starting Out with C++, 3 rd Edition 18 Program 20-1 // This program builds a binary tree with 5 nodes. #include #include "IntBinaryTree.h“ void main(void) { IntBinaryTree tree; cout << "Inserting nodes. "; tree.insertNode(5); tree.insertNode(8); tree.insertNode(3); tree.insertNode(12); tree.insertNode(9); cout << "Done.\n"; }

Starting Out with C++, 3 rd Edition 19 Program 20-1 Figure 20-5 shows the structure of the binary tree built by the program. Note:The shape of the tree is determined by the order in which the values are inserted. The root node in the diagram above holds the value 5 because that was the first value inserted.

Starting Out with C++, 3 rd Edition 20 Traversing the Tree There are three common methods for traversing a binary tree and processing the value of each node: –inorder –preorder –postorder Each of these methods is best implemented as a recursive function.

Starting Out with C++, 3 rd Edition 21 Inorder Traversal 1.The node’s left subtree is traversed. 2.The node’s data is processed. 3.The node’s right subtree is traversed.

Starting Out with C++, 3 rd Edition 22 Preorder Traversal 1.The node’s data is processed. 2.The node’s left subtree is traversed. 3.The node’s right subtree is traversed.

Starting Out with C++, 3 rd Edition 23 Postorder Traversal 1.The node’s left subtree is traversed. 2.The node’s right subtree is traversed. 3.The node’s data is processed.

Starting Out with C++, 3 rd Edition 24 The displayInOrder Member Function void IntBinaryTree::displayInOrder(TreeNode *nodePtr) { if (nodePtr) { displayInOrder(nodePtr->left); cout value right); } }

Starting Out with C++, 3 rd Edition 25 The displayPreOrder Member Function void IntBinaryTree::displayPreOrder(TreeNode *nodePtr) { if (nodePtr) { cout value left); displayPreOrder(nodePtr->right); } }

Starting Out with C++, 3 rd Edition 26 The displayPostOrder Member Function void IntBinaryTree::displayPostOrder(TreeNode *nodePtr) { if (nodePtr) { displayPostOrder(nodePtr->left); displayPostOrder(nodePtr->right); cout value << endl; } }

Starting Out with C++, 3 rd Edition 27 Program 20-2 // This program builds a binary tree with 5 nodes. // The nodes are displayed with inorder, preorder, // and postorder algorithms. #include #include "IntBinaryTree.h“ void main(void) { IntBinaryTree tree; cout << "Inserting nodes.\n"; tree.insertNode(5); tree.insertNode(8); tree.insertNode(3); tree.insertNode(12); tree.insertNode(9);

Starting Out with C++, 3 rd Edition 28 Program 20-2 (continued) cout << "Inorder traversal:\n"; tree.showNodesInOrder(); cout << "\nPreorder traversal:\n"; tree.showNodesPreOrder(); cout << "\nPostorder traversal:\n"; tree.showNodesPostOrder(); }

Starting Out with C++, 3 rd Edition 29 Program 20-2 (continued) Program Output Inserting nodes. Inorder traversal: Preorder traversal:

Starting Out with C++, 3 rd Edition 30 Program 20-2 (continued) Postorder traversal:

Starting Out with C++, 3 rd Edition 31 Searching the Tree The IntBinaryTree class has a public member function, SearchNode, which returns true if a value is found in the tree, or false otherwise. bool IntBinaryTree::searchNode(int num) { TreeNode *nodePtr = root; while (nodePtr) { if (nodePtr->value == num) return true; else if (num value) nodePtr = nodePtr->left; else nodePtr = nodePtr->right; } return false; }

Starting Out with C++, 3 rd Edition 32 Program 20-3 // This program builds a binary tree with 5 nodes. // The SearchNode function determines if the // value 3 is in the tree. #include #include "IntBinaryTree.h“ void main(void) { IntBinaryTree tree; cout << "Inserting nodes.\n"; tree.insertNode(5); tree.insertNode(8); tree.insertNode(3); tree.insertNode(12); tree.insertNode(9);

Starting Out with C++, 3 rd Edition 33 Program 20-3 (continued) if (tree.searchNode(3)) cout << "3 is found in the tree.\n"; else cout << "3 was not found in the tree.\n"; } Program Output Inserting nodes. 3 is found in the tree.

Starting Out with C++, 3 rd Edition 34 Deleting a Node We simply find its parent and set the child pointer that links to it to NULL, and then free the node's memory. But what if we want to delete a node that has child nodes? We must delete the node while at the same time preserving the subtrees that the node links to.

Starting Out with C++, 3 rd Edition 35 Deleting a Node There are two possible situations when we are deleting a non-leaf node: –A) the node has one child, or –B) the node has two children.

Starting Out with C++, 3 rd Edition 36 Deleting a Node Figure 20-6 illustrates a tree in which we are about to delete a node with one subtree.

Starting Out with C++, 3 rd Edition 37 Deleting a Node Figure 20-7 shows how we will link the node's subtree with its parent.

Starting Out with C++, 3 rd Edition 38 Deleting a Node The problem is not as easily solved, however, when the node we are about to delete has two subtrees. For example, look at Figure 20-8.

Starting Out with C++, 3 rd Edition 39 Deleting a Node We cannot attach both of the node's subtrees to its parent, so there must be an alternative solution. One way is to attach the node's right subtree to the parent, and then find a position in the right subtree to attach the left subtree. The result is shown in Figure 20-9.

Starting Out with C++, 3 rd Edition 40 Deleting a Node Figure 20-9.

Starting Out with C++, 3 rd Edition 41 Deleting a Node To delete a node from the IntBinaryTre e, call the public member function remove. The argument is the value of the node that is to be deleted. void IntBinaryTree::remove(int num) { deleteNode(num, root); } The remove member function calls the deleteNode member function. It passes the value of the node to delete, and the root pointer.

Starting Out with C++, 3 rd Edition 42 The deleteNode Member Function void IntBinaryTree::deleteNode(int num, TreeNode *&nodePtr) { if (num value) deleteNode(num, nodePtr->left); else if (num > nodePtr->value) deleteNode(num, nodePtr->right); else makeDeletion(nodePtr); } Notice the declaration of the nodePtr parameter: TreeNode *&nodePtr; nodePtr is not simply a pointer to a TreeNode structure, but a reference to a pointer to a TreeNode structure. Any action performed on nodePtr is actually performed on the argument passed into nodePtr.

Starting Out with C++, 3 rd Edition 43 The deleteNode Member Function else makeDeletion(nodePtr); The trailing else statement calls the makeDeletion function, passing nodePtr as its argument. The makeDeletion function actually deletes the node from the tree, and must reattach the deleted node’s subtrees. Therefore, it must have access to the actual pointer in the binary tree to the node that is being deleted. This is why the nodePtr parameter in the deleteNode function is a reference.

Starting Out with C++, 3 rd Edition 44 The makeDeletion Member Function void IntBinaryTree::makeDeletion(TreeNode *&nodePtr) { TreeNode *tempNodePtr;// Temporary pointer, used in // reattaching the left subtree. if (nodePtr == NULL) cout right == NULL) { tempNodePtr = nodePtr; nodePtr = nodePtr->left; // Reattach the left child delete tempNodePtr; } else if (nodePtr->left == NULL) { tempNodePtr = nodePtr; nodePtr = nodePtr->right; // Reattach the right child delete tempNodePtr; }

Starting Out with C++, 3 rd Edition 45 The makeDeletion Member Function (continued) // If the node has two children. else { // Move one node the right. tempNodePtr = nodePtr->right; // Go to the end left node. while (tempNodePtr->left) tempNodePtr = tempNodePtr->left; // Reattach the left subtree. tempNodePtr->left = nodePtr->left; tempNodePtr = nodePtr; // Reattach the right subtree. nodePtr = nodePtr->right; delete tempNodePtr; } }

Starting Out with C++, 3 rd Edition 46 Program 20-4 // This program builds a binary tree with 5 nodes. // The DeleteNode function is used to remove two // of them. #include #include "IntBinaryTree.h“ void main(void) { IntBinaryTree tree; cout << "Inserting nodes.\n"; tree.insertNode(5); tree.insertNode(8); tree.insertNode(3); tree.insertNode(12); tree.insertNode(9); cout << "Here are the values in the tree:\n"; tree.showNodesInOrder();

Starting Out with C++, 3 rd Edition 47 Program 20-4 (continued) cout << "Deleting 8...\n"; tree.remove(8); cout << "Deleting 12...\n"; tree.remove(12); cout << "Now, here are the nodes:\n"; tree.showNodesInOrder(); }

Starting Out with C++, 3 rd Edition 48 Program 20-4 (continued) Program Output Inserting nodes. Here are the values in the tree: Deleting 8... Deleting Now, here are the nodes: 3 5 9

Starting Out with C++, 3 rd Edition 49 Template Considerations for Binary Trees When designing your template, remember that any data types stored in the binary tree must support the, and == operators. If you use the tree to store class objects, these operators must be overridden.