1 A Two-Level Binary Expression ‘-’ ‘8’ ‘5’ treePtr INORDER TRAVERSAL : 8 - 5 has value 3 PREORDER TRAVERSAL: - 8 5 POSTORDER TRAVERSAL: 8 5 -

Slides:



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

1 A full binary tree A full binary tree is a binary tree in which all the leaves are on the same level and every non leaf node has two children. SHAPE.
©Brooks/Cole, 2003 Chapter 12 Abstract Data Type.
1 Nell Dale Chapter 9 Trees Plus Modified from the slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus C++ Plus Data Structures.
Binary Trees, Binary Search Trees CMPS 2133 Spring 2008.
1 Jake’s Pizza Shop Owner Jake Manager Chef Brad Carol Waitress Waiter Cook Helper Joyce Chris Max Len.
Binary Trees, Binary Search Trees COMP171 Fall 2006.
Trees Chapter 8.
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.
Trees, Binary Trees, and Binary Search Trees COMP171.
Trees Chapter 8. Chapter 8: Trees2 Chapter Objectives To learn how to use a tree to represent a hierarchical organization of information To learn how.
Trees Chapter 8. Chapter 8: Trees2 Chapter Objectives To learn how to use a tree to represent a hierarchical organization of information To learn how.
Priority Queues, Heaps CS3240, L. grewe 1. 2 Goals Describe a priority queue at the logical level and implement a priority queue as a list Describe the.
Heaps CS 308 – Data Structures.
Lists A list is a finite, ordered sequence of data items. Two Implementations –Arrays –Linked Lists.
1 Nell Dale Chapter 9 Trees Plus Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus C++ Plus Data Structures.
Chapter 9 Heaps and Priority Queues. 9-2 What is a Heap? A heap is a binary tree that satisfies these special SHAPE and ORDER properties: –Its shape must.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L12 (Chapter 20) Lists, Stacks,
Unit 11a 1 Unit 11: Data Structures & Complexity H We discuss in this unit Graphs and trees Binary search trees Hashing functions Recursive sorting: quicksort,
Transforming Infix to Postfix
1 CS308 Data Structures An application of binary trees: Binary Expression Trees.
1 C++ Plus Data Structures Nell Dale Chapter 7 Programming with Recursion Modified from the slides by Sylvia Sorkin, Community College of Baltimore County.
9 Priority Queues, Heaps, and Graphs. 9-2 What is a Heap? A heap is a binary tree that satisfies these special SHAPE and ORDER properties: –Its shape.
1 Nell Dale Chapter 9 Trees Plus Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus C++ Plus Data Structures.
Heaps and Priority Queues CS 3358 – Data Structures.
Trees. Tree Terminology Chapter 8: Trees 2 A tree consists of a collection of elements or nodes, with each node linked to its successors The node at the.
Computer Science and Software Engineering University of Wisconsin - Platteville 12. Heap Yan Shi CS/SE 2630 Lecture Notes Partially adopted from C++ Plus.
Advanced Algorithms Analysis and Design Lecture 8 (Continue Lecture 7…..) Elementry Data Structures By Engr Huma Ayub Vine.
1 Joe Meehean. A A B B D D I I C C E E X X A A B B D D I I C C E E X X  Terminology each circle is a node pointers are edges topmost node is the root.
1 Lecture 11 POLYNOMIALS and Tree sort 2 INTRODUCTION EVALUATING POLYNOMIAL FUNCTIONS Horner’s method Permutation Tree sort.
Trees Chapter 8. Chapter 8: Trees2 Chapter Objectives To learn how to use a tree to represent a hierarchical organization of information To learn how.
Spring 2010CS 2251 Trees Chapter 6. Spring 2010CS 2252 Chapter Objectives Learn to use a tree to represent a hierarchical organization of information.
Chapter 9 Priority Queues, Heaps, Graphs, and Sets.
Chapter 9 Priority Queues, Heaps, and Graphs. 2 Goals Describe a priority queue at the logical level and implement a priority queue as a list Describe.
DATA STRUCTURES AND ALGORITHMS Lecture Notes 5 Prepared by İnanç TAHRALI.
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 Trees, Binary Search Trees RIZWAN REHMAN CENTRE FOR COMPUTER STUDIES DIBRUGARH UNIVERSITY.
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.
Chapter 9 Priority Queues, Heaps, Graphs 1 Fall 2010.
1 Nell Dale Chapter 8 Binary Search Trees Modified from the slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus C++ Plus Data.
Chapter 16 – Data Structures and Recursion. Data Structures u Built-in –Array –struct u User developed –linked list –stack –queue –tree Lesson 16.1.
Advance Data Structure 1 College Of Mathematic & Computer Sciences 1 Computer Sciences Department م. م علي عبد الكريم حبيب.
CPSC 252 Binary Heaps Page 1 Binary Heaps A complete binary tree is a binary tree that satisfies the following properties: - every level, except possibly.
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.
Properties: -The value in each node is greater than all values in the node’s subtrees -Complete tree! (fills up from left to right) Max Heap.
2 Binary Heaps What if we’re mostly concerned with finding the most relevant data?  A binary heap is a binary tree (2 or fewer subtrees for each node)
Heaps CS 302 – Data Structures Sections 8.8, 9.1, and 9.2.
1 Nell Dale Chapter 8 Binary Search Trees Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus C++ Plus Data Structures.
Chapter 9 Heaps and Priority Queues Lecture 18. Full Binary Tree Every non-leaf node has two children Leaves are on the same level Full Binary Tree.
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.
1 Trees. 2 Trees Trees. Binary Trees Tree Traversal.
Data Structure By Amee Trivedi.
Chapter 12 – Data Structures
Trees Chapter 15.
Trees Another Abstract Data Type (ADT)
Binary Trees, Binary Search Trees
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 9 Priority Queues, Heaps, Graphs, and Sets
Chapter 21: Binary Trees.
Trees Another Abstract Data Type (ADT)
CS Data Structures Chapter 17 Heaps Mehmet H Gunes
CS Data Structures Chapter 17 Heaps Mehmet H Gunes
Trees Another Abstract Data Type (ADT)
Binary Trees, Binary Search Trees
Heaps and Priority Queues
C++ Plus Data Structures
Chapter 9 The Priority Queue ADT
Binary Trees, Binary Search Trees
Presentation transcript:

1 A Two-Level Binary Expression ‘-’ ‘8’ ‘5’ treePtr INORDER TRAVERSAL : has value 3 PREORDER TRAVERSAL: POSTORDER TRAVERSAL: 8 5 -

2 Levels Indicate Precedence When a binary expression tree is used to represent an expression, the levels of the nodes in the tree indicate their relative precedence of evaluation. Operations at higher levels of the tree are evaluated later than those below them. The operation at the root is always the last operation performed.

3 A Binary Expression Tree ‘*’ ‘+’ ‘4’ ‘3’ ‘2’ What value does it have? ( ) * 3 = 18 What infix, prefix, postfix expressions does it represent?

4 Inorder Traversal: (A + H) / (M - Y) ‘/’ ‘+’ ‘A’ ‘H’ ‘-’ ‘M’‘Y’ tree Print left subtree firstPrint right subtree last Print second

5 Preorder Traversal: / + A H - M Y ‘/’ ‘+’ ‘A’ ‘H’ ‘-’ ‘M’‘Y’ tree Print left subtree secondPrint right subtree last Print first

6 ‘/’ ‘+’ ‘A’ ‘H’ ‘-’ ‘M’‘Y’ tree Print left subtree firstPrint right subtree second Print last Postorder Traversal: A H + M Y - /

7 Evaluate: ‘*’ ‘-’ ‘8’ ‘5’ What infix, prefix, postfix expressions does it represent? ‘/’ ‘+’ ‘4’ ‘3’ ‘2’

8 Answer Infix: ( ( ) * ( ( ) / 3 ) ) Prefix: * / Postfix: / * has operators in order used ‘*’ ‘-’ ‘8’ ‘5’ ‘/’ ‘+’ ‘4’ ‘3’ ‘2’

9 InfoNode has 2 forms enum OpType { OPERATOR, OPERAND } ; struct InfoNode { OpType whichType; union// ANONYMOUS union { char operation ; int operand ; } };. whichType. operation OPERATOR ‘+’. whichType. operand OPERAND 7

10 TreeNodes struct TreeNode { InfoNode info ; // Data member TreeNode* left ; // Pointer to left child TreeNode* right ; // Pointer to right child };. left. info. right NULL whichType. operand OPERAND 7

11 class ExprTree ‘*’ ‘+’ ‘4’ ‘3’ ‘2’ ExprTree ~ExprTree Build Evaluate. private: root

int Eval ( TreeNode* ptr ) // Pre: ptr is a pointer to a binary expression tree. // Post: Function value = the value of the expression represented // by the binary tree pointed to by ptr. { switch ( ptr->info.whichType ) { case OPERAND : return ptr->info.operand ; case OPERATOR : switch ( tree->info.operation ) { case ‘+’ : return ( Eval ( ptr->left ) + Eval ( ptr->right ) ) ; case ‘-’ : return ( Eval ( ptr->left ) - Eval ( ptr->right ) ) ; case ‘*’ : return ( Eval ( ptr->left ) * Eval ( ptr->right ) ) ; case ‘/’ : return ( Eval ( ptr->left ) / Eval ( ptr->right ) ) ; } 12

13 A Full Binary Tree A full binary tree is a binary tree in which all the leaves are on the same level and every non leaf node has two children. SHAPE OF A FULL BINARY TREE

14 A Complete Binary Tree A complete binary tree is a binary tree that is either full or full through the next-to-last level, with the leaves on the last level as far to the left as possible. SHAPE OF A COMPLETE BINARY TREE

15 What is a Heap? A heap is a binary tree that satisfies these special SHAPE and ORDER properties: n Shape: a complete binary tree. n Order: the value stored in each node is greater than or equal to the value in each of its children.

16 Are These Both Heaps? C A T treePtr

tree Is This a Heap?

tree Where is the Largest Element in a Heap?

tree Number the Nodes Left to Right by Level

tree Use the Numbers as Array Indexes to Store the Tree [ 0 ] [ 1 ] [ 2 ] [ 3 ] [ 4 ] [ 5 ] [ 6 ] tree.nodes

// HEAP SPECIFICATION // Assumes ItemType is either a built-in simple data type // or a class with overloaded realtional operators. template struct HeapType { void ReheapDown ( int root, int bottom ) ; void ReheapUp ( int root, int bottom ) ; ItemType* elements ; // ARRAY to be allocated dynamically int numElements ; }; 21

22 Observations l Heap is a struct with member functions l Why not a class? n To allow access to its components n Heaps are usually used in conjunction with other classes which want access to the components but will hide them from the application

23 Reheap Down l For heaps with all but the top element in heap position l How: n Swap root with left or right child n Reheap (down) with that child l Used to remove the highest element: n Remove the root n Put last element in root position n Reheap down to restore the order

24 Reheap Up l For a node that violates a heap up: swap with parent until it is a heap l So, if we added a node to the “end” of the tree, reheap up would put it in the right spot l To build a heap: n start with empty heap n add element to the end and reheap up

25 Exercises l Make a heap out of elements D H A K P R l Remove the top element and reheap.

26 // IMPLEMENTATION OF RECURSIVE HEAP MEMBER FUNCTIONS template void HeapType ::ReheapDown ( int root, int bottom ) // Pre: root is the index of the node that may violate the heap // order property // Post: Heap order property is restored between root and bottom { int maxChild ; int rightChild ; int leftChild ; leftChild = root * ; rightChild = root * ; 26 ReheapDown

if ( leftChild <= bottom )// ReheapDown continued { if ( leftChild == bottom ) maxChild = leftChild ; else { if (elements [ leftChild ] <= elements [ rightChild ] ) maxChild = rightChild ; else maxChild = leftChild ; } if ( elements [ root ] < elements [ maxChild ] ) { Swap ( elements [ root ], elements [ maxChild ] ) ; ReheapDown ( maxChild, bottom ) ; } 27

// IMPLEMENTATIONcontinued template void HeapType ::ReheapUp ( int root, int bottom ) // Pre: bottom is the index of the node that may violate the heap // order property. The order property is satisfied from root to // next-to-last node. // Post: Heap order property is restored between root and bottom { int parent ; if ( bottom > root ) { parent = ( bottom - 1 ) / 2; if ( elements [ parent ] < elements [ bottom ] ) { Swap ( elements [ parent ], elements [ bottom ] ) ; ReheapUp ( root, parent ) ; } 28

29 Priority Queue A priority queue is an ADT with the property that only the highest-priority element can be accessed at any time. Example: homework assignments are ordered by priority. Like a sorted list except for the access restriction. Goal: be able to insert in order and to access the top element efficiently.

ADT Priority Queue Operations Transformers n MakeEmpty n Enqueue n Dequeue Observers n IsEmpty n IsFull change state observe state 30

// CLASS PQTYPE DEFINITION AND MEMBER FUNCTIONS // template class PQType { public: PQType( int ); ~PQType ( ); void MakeEmpty( ); bool IsEmpty( ) const; bool IsFull( ) const; void Enqueue( ItemType item ); void Dequeue( ItemType& item ); private: int numItems; HeapType items; int maxItems; }; 31

PQType ~PQType Enqueue Dequeue. class PQType [0] [1] [2] [3] [4] [5] [6] [7] [8] [9] ‘X’ ‘C’ ‘J’ Private Data: numItems 3 maxItems 10 items.elements.numElements

33 Graphs A data structure that consists of a set of nodes (vertices) and arcs (edges) that relate the nodes to each other. G = (V, E) E.g. a map with V = cities and E = roads Undirected versus directed: some of the streets may be one-way. Weighted: each edge has a value (miles).

Applications Traversal: Find a route (path) from Boston to Chicago. Find the shortest path. Approaches: Depth-first search Breadth-first search 34

35 Implementation via Adjacency Matrices l For a graph with N vertices: numVertices = the number of nodes vertices[N] = name of vertex N edges[N] [M] = weight from vertex N to M l See p l How do you add a vertex? An edge? l How do you find a path?

36 Implementation via Adjacency Lists l An array of vertices. l Each vertex has a linked list of the nodes extending directly from it. l See p l When would you use this? When not?