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

Slides:



Advertisements
Similar presentations
S. Sudarshan Based partly on material from Fawzi Emad & Chau-Wen Tseng
Advertisements

Binary Trees Chapter 6. Linked Lists Suck By now you realize that the title to this slide is true… By now you realize that the title to this slide is.
Binary Trees, Binary Search Trees CMPS 2133 Spring 2008.
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.
BST Data Structure A BST node contains: A BST contains
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.
Chapter 12 Trees. Copyright © 2005 Pearson Addison-Wesley. All rights reserved Chapter Objectives Define trees as data structures Define the terms.
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.
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
Chapter 08 Binary Trees and Binary Search Trees © John Urrutia 2013, All Rights Reserved.
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.
Recursion Bryce Boe 2013/11/18 CS24, Fall Outline Wednesday Recap Lab 7 Iterative Solution Recursion Binary Tree Traversals Lab 7 Recursive Solution.
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.
CS Data Structures Chapter 15 Trees Mehmet H Gunes
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.
Binary Trees Chapter 10. Introduction Previous chapter considered linked lists –nodes connected by two or more links We seek to organize data in a linked.
1 Trees A tree is a data structure used to represent different kinds of data and help solve a number of algorithmic problems Game trees (i.e., chess ),
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.
Binary Search Trees Binary Search Trees (BST)  the tree from the previous slide is a special kind of binary tree called a binary.
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.
Review 1 Queue Operations on Queues A Dequeue Operation An Enqueue Operation Array Implementation Link list Implementation Examples.
Binary Trees Chapter 10. Introduction Previous chapter considered linked lists –nodes connected by two or more links We seek to organize data in a linked.
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. 1 Chapter 19 Binary Search Trees.
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.
1/14/20161 BST Operations Data Structures Ananda Gunawardena.
1 Chapter 4 Trees Basic concept How tree are used to implement the file system How tree can be used to evaluate arithmetic expressions How to use trees.
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 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.
1. Iterative Preorder Traversal Rpreorder(T) 1. [process the root node] if T!= NULL then Write Data(T) else Write “empty Tree” 2. [process the left subtree]
Copyright © 2012 Pearson Education, Inc. Chapter 20: Binary Trees.
Data Structures: A Pseudocode Approach with C, Second Edition 1 Chapter 7 Objectives Create and implement binary search trees Understand the operation.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 20: Binary Trees.
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.
(c) University of Washington20-1 CSC 143 Java Trees.
DS.T.1 Trees Chapter 4 Overview Tree Concepts Traversals Binary Trees Binary Search Trees AVL Trees Splay Trees B-Trees.
Binary Search Trees Chapter 7 Objectives
Definition and Application of Binary Trees
Binary Search Trees Chapter 7 Objectives
Binary Search Tree (BST)
Lecture 22 Binary Search Trees Chapter 10 of textbook
Section 8.1 Trees.
Chapter 20: Binary Trees.
Chapter 21: Binary Trees.
Find in a linked list? first last 7  4  3  8 NULL
Prepared by: S. Kondakci
Binary Search Trees Chapter 7 Objectives
CSC 143 Java Trees.
Chapter 20: Binary Trees.
Trees.
Data Structures Using C++ 2E
Tree (new ADT) Terminology: A tree is a collection of elements (nodes)
Presentation transcript:

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

Starting Out with C++, 3 rd Edition 2 Definition and Applications of Binary Trees A binary tree is a non-linear linked list where each node may point to at most 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 Every node in the tree is reachable from the root node. The root node has no predecessor; every other node has only one predecessor.

Starting Out with C++, 3 rd Edition 5 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 6 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 7 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 8 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 9 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 10 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 11 Activities for Binary Trees Count the number of leaves in a tree. Find the height of the tree. Evaluate the tree (if it represents an expression tree). Is the tree strictly binary; every node has exactly two children or none.

Starting Out with C++, 3 rd Edition 12 Activities for Binary Trees Is tree leftist? Every node that has only one child, has a left child, but no right child. Is every node equal or greater than both children? Count the number of times a value appears in the tree. Print the tree by level. Need to use a queue.

Starting Out with C++, 3 rd Edition 13 Activities for Binary Trees Is the tree balanced? Height of left subtree and height of right subtree differ by at most 1. Given the following traversals, construct the tree. Is the tree unique? –Preorder – TOERRISHUMAN –Inorder – EORSIAMUNHRT

Starting Out with C++, 3 rd Edition 14 Activities for Binary Trees Reflect a binary tree. Exchange left and right children throughout. Are two tree similar? Does each tree have same branching structures, but possibly different node values. Are two trees mirror images of each other?

Starting Out with C++, 3 rd Edition 15 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 16 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 the figure below. 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 17 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 18 Definition and Applications of Binary Trees This process continues until the value is found. The figure below illustrates the search pattern for finding the value P in the binary tree.

Starting Out with C++, 3 rd Edition 19 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 class declaration (in the file TreeNode.h ): class TreeNode { public: int value; TreeNode *left; TreeNode *right; TreeNode ( int v, TreeNode *l = NULL, TreeNode *r = NULL ) { value = v; left = l; right = r; } }; // TreeNode The class is implemented in the class shown next…

Starting Out with C++, 3 rd Edition 20 IntBinaryTree.h #include "TreeNode.h" class IntBinaryTree { private: TreeNode *root; void insertAux ( TreeNode *&, int ); bool searchAux ( TreeNode *, int ); void destroySubTree ( TreeNode * ); void deleteAux ( TreeNode *&, int ); void makeDeletion ( TreeNode *& ); void displayInOrder ( TreeNode * ); void displayPreOrder ( TreeNode * ); void displayPostOrder ( TreeNode * );

Starting Out with C++, 3 rd Edition 21 IntBinaryTree.h (cont) public: IntBinaryTree ( void ){ root = NULL; } ~IntBinaryTree ( void ) { destroySubTree( root ); } void insertNode ( int v ) { insertAux( root, v ); } bool searchTree ( int v ) { searchAux( root, v); } void deleteNode ( int ) { deleteAux( root, v ); } void showNodesInOrder ( void ) { displayInOrder( root ); } void showNodesPreOrder( void ) { displayPreOrder( root ); } void showNodesPostOrder( void ) { displayPostOrder( root ); } }; // IntBinaryTree

Starting Out with C++, 3 rd Edition 22 insertAux void IntBinaryTree::insertAux( TreeNode *& tn, int v ) { if ( !tn ) { tn = new TreeNode( v ); assert( tn ); } // if else if ( tn->value < v ) insertAux( tn->right, v ); else insertAux( tn->left, v ); } // IntBinaryTree::insertAux

Starting Out with C++, 3 rd Edition 23 Inserting into a Binary Tree #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"; } // main

Starting Out with C++, 3 rd Edition 24 Binary Tree that is built The figure below 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 25 displayInOrder void IntBinaryTree::displayInOrder ( TreeNode *tn ) { if ( tn ) { displayInOrder( tn->left ); cout value right ); } // if } // IntBinaryTree::displayInOrder

Starting Out with C++, 3 rd Edition 26 displayPreOrder void IntBinaryTree::displayPreOrder ( TreeNode *tn ) { if ( tn ) { cout value left ); displayPreOrder( tn->right ); } // if } // IntBinaryTree::displayPreOrder

Starting Out with C++, 3 rd Edition 27 displayPostOrder void IntBinaryTree::displayPostOrder ( TreeNode *tn ) { if ( tn ) { displayPostOrder( tn->left ); displayPostOrder( tn->right ); cout value << endl; } // if } // IntBinaryTree::displayPostOrder

Starting Out with C++, 3 rd Edition 28 Inserting and Printing Binary Trees 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 << "Inorder traversal:\n"; tree.showNodesInOrder(); cout << "\nPreorder traversal:\n"; tree.showNodesPreOrder(); cout << "\nPostorder traversal:\n"; tree.showNodesPostOrder(); } // main

Starting Out with C++, 3 rd Edition 29 Output Inserting nodes. Inorder traversal: Preorder traversal: Postorder traversal:

Starting Out with C++, 3 rd Edition 30 searchAux bool IntBinaryTree::searchAux ( TreeNode *tn, int v ) { if ( !tn ) return false; else if ( tn->value == v ) return true; else if ( tn->value < v ) return searchAux( tn->right, v ); else return searchAux( tn->left, v ); } // IntBinaryTree::searchAux

Starting Out with C++, 3 rd Edition 31 Deleting a Node Deleting a leaf node is easy. 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 32 Deleting a Node There are two possible situations when we are deleting a non-leaf node: –the node has one child, or –the node has two children.

Starting Out with C++, 3 rd Edition 33 Deleting a Node Deleting a node with one subtree.

Starting Out with C++, 3 rd Edition 34 Deleting a Node The figure shows how we will link the node's subtree with its parent.

Starting Out with C++, 3 rd Edition 35 Deleting a Node The problem is not as easily solved, however, when the node we are about to delete has two subtrees.

Starting Out with C++, 3 rd Edition 36 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 as follows.

Starting Out with C++, 3 rd Edition 37 Deleting a Node

Starting Out with C++, 3 rd Edition 38 deleteAux void IntBinaryTree::deleteAux ( TreeNode *&treePtr, int num ) { if ( num value ) deleteAux( treePtr->left, num ); else if ( num > treePtr->value ) deleteAux( treePtr->right, num ); else makeDeletion( treePtr ); } // IntBinaryTree::deleteNode

Starting Out with C++, 3 rd Edition 39 makeDeletion void IntBinaryTree::makeDeletion ( TreeNode *&treePtr ) { TreeNode *tempNodePtr; if ( !treePtr ) cout right ) { tempNodePtr = treePtr; treePtr = treePtr->left; // Reattach the left child delete tempNodePtr; } // else if else if ( !treePtr->left ) { tempNodePtr = nodePtr; treePtr = treePtr->right; // Reattach the right child delete tempNodePtr; } // else if

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

Starting Out with C++, 3 rd Edition 41 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.

Starting Out with C++, 3 rd Edition 42 Activities for BST’s Is the tree in BST order? Delete the smallest element in a BST. Alter the BST so that parent pointers are stored at each node. Show insert/delete with parent pointers.