Trees. Trees Traversal Inorder  (Left) Root (Right) Preorder  Root (Left) (Right) Postorder  (Left) (Right) Root Root LeftRight.

Slides:



Advertisements
Similar presentations
Chapter 17 Linked Lists.
Advertisements

S. Sudarshan Based partly on material from Fawzi Emad & Chau-Wen Tseng
Senem Kumova Metin Spring2009 BINARY TREES && TREE TRAVERSALS Chapter 10 in A Book on C.
1 Jake’s Pizza Shop Owner Jake Manager Chef Brad Carol Waitress Waiter Cook Helper Joyce Chris Max Len.
Main Index Contents 11 Main Index Contents Tree StructuresTree Structures (3 slides) Tree Structures Tree Node Level and Path Len. Tree Node Level and.
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.
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.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 19: Binary Trees.
More Trees COL 106 Amit Kumar and Shweta Agrawal Most slides courtesy : Douglas Wilhelm Harder, MMath, UWaterloo
CS 146: Data Structures and Algorithms June 18 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak
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.
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.
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.
1 CSE 1342 Programming Concepts Trees. 2 Basic Terminology Trees are made up of nodes and edges. A tree has a single node known as a root. –The root is.
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,
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.
BINARY SEARCH TREE. Binary Trees A binary tree is a tree in which no node can have more than two children. In this case we can keep direct links to the.
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.
Tree Data Structures.
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.
Binary Search Tree Traversal Methods. How are they different from Binary Trees?  In computer science, a binary tree is a tree data structure in which.
 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 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)
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.
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.
Chapter 12 – Data Structures
Definition and Application of Binary Trees
Data Structure and Algorithms
COMP 53 – Week Fourteen Trees.
List ADT & Linked Lists.
Binary Search Tree (BST)
CMSC 341 Introduction to Trees.
Binary Search 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.
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
Pointers & Dynamic Data Structures
Chapter 20: Binary Trees.
Data Structures Using C++ 2E
Binary Search Tree.
Presentation transcript:

Trees

Trees Traversal Inorder  (Left) Root (Right) Preorder  Root (Left) (Right) Postorder  (Left) (Right) Root Root LeftRight

Traversal of Binary Trees Pass through all nodes of tree Inorder (symmetric traversal) Preorder (depth first traversal) Postorder

Trees Traversal Inorder  (Left) Root (Right) Preorder  Root (Left) (Right) Postorder  (Left) (Right) Root Root LeftRight

Inorder Traversal Left Root Right manner Left + Right [Left*Right]+[Left+Right] (A*B)+[(Left*Right)+E) (A*B)+[(C*D)+E] + *+ AB*E CD (A*B)+(C*D+E)

Preorder Traversal Root Left Right manner + Left Right + [*Left Right] [+Left Right] +(*AB) [+ *Left Right E] +*AB + *C D E + *+ AB*E CD

Postorder Traversal Left Right Root manner Left Right + [Left Right *] [Left Right+] + (AB*) [Left Right * E + ]+ (AB*) [C D * E + ]+ AB* C D * E *+ AB*E CD

Binary Search Tree Elements are sorted: For any node n in a binary search tree:  The value at n is greater than the values of any of the nodes in its left subtree  The value at n is less than the values of any of the nodes in its right subtree  Its left and right subtrees are binary search trees Need to define “greater than” and “less than” for the specific data

Expression Trees Expression tree for: (a+b*c) +((d*e+f)*g) Inorder traversal Preorder traversal Postorder traversal

Algorithm to convert postfix expression into expression tree e.g. input: ab+cde+** Expression Trees

For every node, X, in the tree, the values of all the keys in its left subtree are smaller than the key value of X, and the values of all the keys in its right subtree are larger than the key value of X.  X Binary Search Tree

Binary Search Tree Operations There are many operations one can perform on a binary search tree. a) Creating a binary search tree b) Inserting a node into a binary search tree c) Finding a node in a binary search tree d) Deleting a node in a binary search tree. We will use a simple class that implements a binary tree to store integer values. Creating a Binary Tree We create an IntBinaryTree class.

The basic node of our binary tree has the following struct declaration. struct TreeNode { int value; TreeNode *left; TreeNode *right; } The class IntBinaryTree declaration is - IntBinaryTree.h class IntBinaryTree { private: 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 *); 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); } };

The root pointer is the pointer to the binary tree. This is similar to the head pointer in a linked list. The root pointer will point to the first node in the tree, or to NULL (if the tree is empty). It is initialized in the constructor. The destructor calls destroySubTree, a private member function, that recursively deletes all the nodes in the tree. Inserting a Node The code to insert a new value in the tree is fairly straightforward. First, a new node is allocated, and its value member is initialized with the new value.

Note, we assume that our binary tree will store no duplicate values. 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;

while (nodePtr != NULL) { if (num value) { if (nodePtr->left) nodePtr = nodePtr->left; else { nodePtr->left = newNode; break; } } 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; } } } }

Program // 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"; }

Program Figure 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.

The IntBinaryTree class can display all the values in the tree using all 3 of these algorithms. The algorithms are initiated by the following inline public member functions - void showNodesInOrder(void) {displayInOrder(root); } void showNodesPreOrder() {displayPreOrder(root); } void showNodesPostOrder() {displayPostOrder(root); } Each of these public member functions calls a recursive private member function, and passes the root pointer as argument. The code for these recursive functions is simple -

void IntBinaryTree:: displayInOrder (TreeNode *nodePtr) { if (nodePtr) { displayInOrder(nodePtr->left); cout value right); } } void IntBinaryTree:: displayPreOrder (TreeNode *nodePtr) { if (nodePtr) { cout value left); displayPreOrder(nodePtr->right); } }

void IntBinaryTree:: displayPostOrder (TreeNode *nodePtr) { if (nodePtr) { displayPostOrder(nodePtr->left); displayPostOrder(nodePtr->right); cout value << endl; } }

Program // 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);

cout << "Inorder traversal:\n"; tree.showNodesInOrder(); cout << "\nPreorder traversal:\n"; tree.showNodesPreOrder(); cout << "\nPostorder traversal:\n"; tree.showNodesPostOrder(); } Program Output Inserting nodes. Inorder traversal:

Preorder traversal: Postorder traversal: As an intellectual exercise, convince yourself that for each of the 3 algorithms, the 3 output orders of the values of the 3 traversals are correct.

Searching the Tree The IntBinaryTree class has a public member function called searchNode, that returns true if a value is found in the tree, or false otherwise. The function starts at the root node, and traverses the tree, until it finds the search value, or runs out of nodes. 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; }

Program // 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);

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. Deleting a Node To delete a leaf node is easy - a) Find its parent b) Set the child pointer that links to it to NULL c) Free the node’s memory

How to delete a node if it has child nodes? We want to delete the node, but preserve the sub-trees, that the node links to. There are 2 possible situations to be faced when deleting a non leaf node - 1) The node has one child. 2) The node has two children.

The problem is not as easily solved if the node has two children.

We cannot attach both of the node’s subtrees to its parent. One solution is to - a) find a position in the right subtree to attach the left subtree. b) attach the node’s right subtree to the parent

Now the code - to delete a node from the IntBinaryTree, call the public member remove. The argument passed to the function is the value of the node you want to delete.

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. The deleteNode member function is shown below -

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 The reason for doing this is explained shortly. The deleteNode function uses an if/else statement.

if(num value) deleteNode(num, nodePtr->left); The above statement compares the parameter num with the value member of the node that nodePtr point to. If num is less, the value being searched for will appear somewhere in the nodePtr’s left subtree (if it appears at all). So recall the deleteNode function recursively, with num as the first argument, and nodePtr->left as the second argument. If num is not less than nodePtr->value, the the following else if statement is executed. else if(num > nodePtr->value) deleteNode(num, nodePtr->right);

If num is greater than nodePtr->value, then the value being searched for will appear somewhere in nodePtr’s right subtree (if it appears in the tree at all). If num is equal to nodePtr->value, then neither of the if statements above will find a true condition. So, nodePtr points to the node to be deleted, and the trailing else will be executed. else makeDeletion(nodePtr); The makeDeletion function actually deletes the node from the tree and reattaches the deleted node’s sub trees.

It must have access to the actual pointer in the tree to the node that is being deleted (not just a copy of the pointer). This is why the nodePtr parameter in the deleteNode function is a reference. It must pass to makeDeletion, the actual pointer, to the node to be deleted. 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; } // 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; } }

Program // 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();

cout << "Deleting 8...\n"; tree.remove(8); cout << "Deleting 12...\n"; tree.remove(12); cout << "Now, here are the nodes:\n"; tree.showNodesInOrder(); } Program Output Inserting nodes. Here are the values in the tree: Deleting 8... Deleting Now, here are the nodes: 3 5 9