CS 1031 Tree Traversal Techniques; Heaps Tree Traversal Concept Tree Traversal Techniques: Preorder, Inorder, Postorder Full Trees Almost Complete Trees.

Slides:



Advertisements
Similar presentations
Binary Trees CSC 220. Your Observations (so far data structures) Array –Unordered Add, delete, search –Ordered Linked List –??
Advertisements

Comp 122, Spring 2004 Binary Search Trees. btrees - 2 Comp 122, Spring 2004 Binary Trees  Recursive definition 1.An empty tree is a binary tree 2.A node.
1 A Two-Level Binary Expression ‘-’ ‘8’ ‘5’ treePtr INORDER TRAVERSAL : has value 3 PREORDER TRAVERSAL: POSTORDER TRAVERSAL: 8 5 -
Binary Trees, Binary Search Trees CMPS 2133 Spring 2008.
Binary Trees, Binary Search Trees COMP171 Fall 2006.
CS 171: Introduction to Computer Science II
1 Chapter 6 Priority Queues (Heaps) General ideas of priority queues (Insert & DeleteMin) Efficient implementation of priority queue Uses of priority queues.
CS 315 March 24 Goals: Heap (Chapter 6) priority queue definition of a heap Algorithms for Insert DeleteMin percolate-down Build-heap.
1 Nell Dale Chapter 9 Trees Plus Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus C++ Plus Data Structures.
Version TCSS 342, Winter 2006 Lecture Notes Priority Queues Heaps.
Binary Trees A binary tree is made up of a finite set of nodes that is either empty or consists of a node called the root together with two binary trees,
Lec 15 April 9 Topics: l binary Trees l expression trees Binary Search Trees (Chapter 5 of text)
Source: Muangsin / Weiss1 Priority Queue (Heap) A kind of queue Dequeue gets element with the highest priority Priority is based on a comparable value.
Chapter 12 Trees. Copyright © 2005 Pearson Addison-Wesley. All rights reserved Chapter Objectives Define trees as data structures Define the terms.
Fundamentals of Python: From First Programs Through Data Structures
Data Structures Using C++ 2E Chapter 11 Binary Trees and B-Trees.
More Trees COL 106 Amit Kumar and Shweta Agrawal Most slides courtesy : Douglas Wilhelm Harder, MMath, UWaterloo
Binary Trees A binary tree is made up of a finite set of nodes that is either empty or consists of a node called the root together with two binary trees.
1 Nell Dale Chapter 9 Trees Plus Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus C++ Plus Data Structures.
PRIORITY QUEUES (HEAPS). Queues are a standard mechanism for ordering tasks on a first-come, first-served basis However, some tasks may be more important.
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.
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 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 ),
For Monday Read Weiss, chapter 7, sections 1-3. Homework –Weiss, chapter 4, exercise 6. Make sure you include parentheses where appropriate.
Binary Trees, Binary Search Trees RIZWAN REHMAN CENTRE FOR COMPUTER STUDIES DIBRUGARH UNIVERSITY.
Chapter 21 Priority Queue: Binary Heap Saurav Karmakar.
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, Binary Trees, and Binary Search Trees COMP171.
Starting at Binary Trees
CS 1031 Trees A Quick Introduction to Graphs Definition of Trees Rooted Trees Binary Trees Binary Search Trees.
Preview  Graph  Tree Binary Tree Binary Search Tree Binary Search Tree Property Binary Search Tree functions  In-order walk  Pre-order walk  Post-order.
Priority Queues and Heaps. October 2004John Edgar2  A queue should implement at least the first two of these operations:  insert – insert item at the.
Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Modified for use at Midwestern State University Chapter.
1 Trees A Quick Introduction to Graphs Definition of Trees Rooted Trees Binary Trees Binary Search Trees.
+ David Kauchak cs312 Review. + Midterm Will be posted online this afternoon You will have 2 hours to take it watch your time! if you get stuck on a problem,
CE 221 Data Structures and Algorithms Chapter 6: Priority Queues (Binary Heaps) Text: Read Weiss, §6.1 – 6.3 1Izmir University of Economics.
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 Trees (BST)
FALL 2005CENG 213 Data Structures1 Priority Queues (Heaps) Reference: Chapter 7.
AVL Trees and Heaps. AVL Trees So far balancing the tree was done globally Basically every node was involved in the balance operation Tree balancing can.
Copyright © 2012 Pearson Education, Inc. Chapter 20: Binary Trees.
Data Structures Using C++ 2E Chapter 11 Binary Trees.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 20: Binary Trees.
CS 367 Introduction to Data Structures Lecture 8.
BINARY TREES Objectives Define trees as data structures Define the terms associated with trees Discuss tree traversal algorithms Discuss a binary.
Course: Programming II - Abstract Data Types HeapsSlide Number 1 The ADT Heap So far we have seen the following sorting types : 1) Linked List sort by.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 20: Binary Trees.
CS 201 Data Structures and Algorithms
Week 6 - Wednesday CS221.
Binary Search Tree (BST)
Source: Muangsin / Weiss
Binary Trees, Binary Search Trees
Chapter 20: Binary Trees.
Chapter 22 : Binary Trees, AVL Trees, and Priority Queues
Ch. 11 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
Ch. 8 Priority Queues And Heaps
CE 221 Data Structures and Algorithms
Binary Trees, Binary Search Trees
Chapter 20: Binary Trees.
Trees A Quick Introduction to Graphs Definition of Trees Rooted Trees
C++ Plus Data Structures
Binary Trees, Binary Search Trees
Data Structures Using C++ 2E
Tree (new ADT) Terminology: A tree is a collection of elements (nodes)
Presentation transcript:

CS 1031 Tree Traversal Techniques; Heaps Tree Traversal Concept Tree Traversal Techniques: Preorder, Inorder, Postorder Full Trees Almost Complete Trees Heaps

CS 1032 Binary-Tree Related Definitions The children of any node in a binary tree are ordered into a left child and a right child A node can have a left and a right child, a left child only, a right child only, or no children The tree made up of a left child (of a node x) and all its descendents is called the left subtree of x Right subtrees are defined similarly

CS 1033 A Binary-tree Node Class class TreeNode { public: typedef int datatype; TreeNode(datatype x=0, TreeNode *left=NULL, TreeNode *right=NULL){ data=x; this->left=left; this->right=right; }; datatype getData( ) {return data;}; TreeNode *getLeft( ){return left;}; TreeNode *getRight( ){return right;}; void setData(datatype x) {data=x;}; void setLeft(TreeNode *ptr) {left=ptr;}; void setRight(TreeNode *ptr) {right=ptr;}; private: datatype data; // different data type for other apps TreeNode *left; // the pointer to left child TreeNode *right; // the pointer to right child };

CS 1034 Binary Tree Class class Tree { public: typedef int datatype; Tree(TreeNode *rootPtr=NULL){this->rootPtr=rootPtr;}; TreeNode *search(datatype x); bool insert(datatype x); TreeNode * remove(datatype x); TreeNode *getRoot(){return rootPtr;}; Tree *getLeftSubtree(); Tree *getRightSubtree(); bool isEmpty(){return rootPtr == NULL;}; private: TreeNode *rootPtr; };

CS 1035 Binary Tree Traversal Traversal is the process of visiting every node once Visiting a node entails doing some processing at that node, but when describing a traversal strategy, we need not concern ourselves with what that processing is

CS 1036 Binary Tree Traversal Techniques Three recursive techniques for binary tree traversal In each technique, the left subtree is traversed recursively, the right subtree is traversed recursively, and the root is visited What distinguishes the techniques from one another is the order of those 3 tasks

CS 1037 Preoder, Inorder, Postorder In Preorder, the root is visited before (pre) the subtrees traversals In Inorder, the root is visited in-between left and right subtree traversal In Preorder, the root is visited after (pre) the subtrees traversals Preorder Traversal: 1.Visit the root 2.Traverse left subtree 3.Traverse right subtree Inorder Traversal: 1.Traverse left subtree 2.Visit the root 3.Traverse right subtree Postorder Traversal: 1.Traverse left subtree 2.Traverse right subtree 3.Visit the root

CS 1038 Illustrations for Traversals Assume: visiting a node is printing its label Preorder: Inorder: Postorder:

CS 1039 Illustrations for Traversals (Contd.) Assume: visiting a node is printing its data Preorder: Inorder: Postorder:

CS Code for the Traversal Techniques The code for visit is up to you to provide, depending on the application A typical example for visit(…) is to print out the data part of its input node void inOrder(Tree *tree){ if (tree->isEmpty( )) return; inOrder(tree->getLeftSubtree( )); visit(tree->getRoot( )); inOrder(tree->getRightSubtree( )); } void preOrder(Tree *tree){ if (tree->isEmpty( )) return; visit(tree->getRoot( )); preOrder(tree->getLeftSubtree()); preOrder(tree->getRightSubtree()); } void postOrder(Tree *tree){ if (tree->isEmpty( )) return; postOrder(tree->getLeftSubtree( )); postOrder(tree->getRightSubtree( )); visit(tree->getRoot( )); }

CS Application of Traversal Sorting a BST Observe the output of the inorder traversal of the BST example two slides earlier It is sorted This is no coincidence As a general rule, if you output the keys (data) of the nodes of a BST using inorder traversal, the data comes out sorted in increasing order

CS Other Kinds of Binary Trees (Full Binary Trees) Full Binary Tree: A full binary tree is a binary tree where all the leaves are on the same level and every non-leaf has two children The first four full binary trees are:

CS Examples of Non-Full Binary Trees These trees are NOT full binary trees: (do you know why?)

CS Canonical Labeling of Full Binary Trees Label the nodes from 1 to n from the top to the bottom, left to right Relationships between labels of children and parent: 2i 2i+1 i

CS Other Kinds of Binary Trees (Almost Complete Binary trees) Almost Complete Binary Tree: An almost complete binary tree of n nodes, for any arbitrary nonnegative integer n, is the binary tree made up of the first n nodes of a canonically labeled full binary

CS Depth/Height of Full Trees and Almost Complete Trees The height (or depth ) h of such trees is O(log n) Proof: In the case of full trees, –The number of nodes n is: n= …+2 h =2 h+1 -1 –Therefore, 2 h+1 = n+1, and thus, h=log(n+1)-1 –Hence, h=O(log n) For almost complete trees, the proof is left as an exercise.

CS Canonical Labeling of Almost Complete Binary Trees Same labeling inherited from full binary trees Same relationship holding between the labels of children and parents: Relationships between labels of children and parent: 2i 2i+1 i

CS Array Representation of Full Trees and Almost Complete Trees A canonically label-able tree, like full binary trees and almost complete binary trees, can be represented by an array A of the same length as the number of nodes A[k] is identified with node of label k That is, A[k] holds the data of node k Advantage: –no need to store left and right pointers in the nodes  save memory –Direct access to nodes: to get to node k, access A[k]

CS Illustration of Array Representation Notice: Left child of A[5] (of data 11) is A[2*5]=A[10] (of data 18), and its right child is A[2*5+1]=A[11] (of data 12). Parent of A[4] is A[4/2]=A[2], and parent of A[5]=A[5/2]=A[2]

CS Adjustment of Indexes Notice that in the previous slides, the node labels start from 1, and so would the corresponding arrays But in C/C++, array indices start from 0 The best way to handle the mismatch is to adjust the canonical labeling of full and almost complete trees. Start the node labeling from 0 (rather than 1). The children of node k are now nodes (2k+1) and (2k+2), and the parent of node k is (k-1)/2, integer division.

CS Application of Almost Complete Binary Trees: Heaps A heap (or min-heap to be precise) is an almost complete binary tree where –Every node holds a data value (or key) –The key of every node is ≤ the keys of the children Note: A max-heap has the same definition except that the Key of every node is >= the keys of the children

CS Example of a Min-heap

CS Operations on Heaps Delete the minimum value and return it. This operation is called deleteMin. Insert a new data value Applications of Heaps: A heap implements a priority queue, which is a queue that orders entities not a on first-come first-serve basis, but on a priority basis: the item of highest priority is at the head, and the item of the lowest priority is at the tail Another application: sorting, which will be seen later

CS DeleteMin in Min-heaps The minimum value in a min-heap is at the root! To delete the min, you can’t just remove the data value of the root, because every node must hold a key Instead, take the last node from the heap, move its key to the root, and delete that last node But now, the tree is no longer a heap (still almost complete, but the root key value may no longer be ≤ the keys of its children

CS Illustration of First Stage of deletemin

CS Restore Heap To bring the structure back to its “heapness”, we restore the heap Swap the new root key with the smaller child. Now the potential bug is at the one level down. If it is not already ≤ the keys of its children, swap it with its smaller child Keep repeating the last step until the “bug” key becomes ≤ its children, or the it becomes a leaf

CS Illustration of Restore-Heap Now it is a correct heap

CS Time complexity of insert and deletmin Both operations takes time proportional to the height of the tree –When restoring the heap, the bug moves from level to level until, in the worst case, it becomes a leaf (in deletemin) or the root (in insert) –Each move to a new level takes constant time –Therefore, the time is proportional to the number of levels, which is the height of the tree. But the height is O(log n) Therefore, both insert and deletemin take O(log n) time, which is very fast.

CS Inserting into a minheap Suppose you want to insert a new value x into the heap Create a new node at the “end” of the heap (or put x at the end of the array) If x is >= its parent, done Otherwise, we have to restore the heap: –Repeatedly swap x with its parent until either x reaches the root of x becomes >= its parent

CS Illustration of Insertion Into the Heap In class

CS The Min-heap Class in C++ class Minheap{ //the heap is implemented with a dynamic array public: typedef int datatype; Minheap(int cap = 10){capacity=cap; length=0; ptr = new datatype[cap];}; datatype deleteMin( ); void insert(datatype x); bool isEmpty( ) {return length==0;}; int size( ) {return length;}; private: datatype *ptr; // points to the array int capacity; int length; void doubleCapacity(); //doubles the capacity when needed };

CS Code for deletemin Minheap::datatype Minheap::deleteMin( ){ assert(length>0); datatype returnValue = ptr[0]; length--; ptr[0]=ptr[length]; // move last value to root element int i=0; while ((2*i+1 ptr[2*i+1]) || (2*i+2 ptr[2*i+1] || ptr[i]>ptr[2*i+2]))){ // “bug” still > at least one child if (ptr[2*i+1] <= ptr[2*i+2]){ // left child is the smaller child datatype tmp= ptr[i]; ptr[i]=ptr[2*i+1]; ptr[2*i+1]=tmp; //swap i=2*i+1; } else{ // right child if the smaller child. Swap bug with right child. datatype tmp= ptr[i]; ptr[i]=ptr[2*i+2]; ptr[2*i+2]=tmp; // swap i=2*i+2; } } return returnValue; };

CS Code for Insert void Minheap::insert(datatype x){ if (length==capacity) doubleCapacity(); ptr[length]=x; int i=length; length++; while (i>0 && ptr[i] < ptr[i/2]){ datatype tmp= ptr[i]; ptr[i]=ptr[(i-1)/2]; ptr[(i-1)/2]=tmp; i=(i-1)/2; } };

CS Code for doubleCapacity void Minheap::doubleCapacity(){ capacity = 2*capacity; datatype *newptr = new datatype[capacity]; for (int i=0;i<length;i++) newptr[i]=ptr[i]; delete [] ptr; ptr = newptr; };