§3 Binary Tree Traversals —— visit each node exactly once L ::= move left ; R ::= move right ; V ::= visit the node. We will always traverse the left.

Slides:



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

Trees Types and Operations
S. Sudarshan Based partly on material from Fawzi Emad & Chau-Wen Tseng
1 Heap and Others 黃兆武. 2 Heap A max tree is a tree in which the key value in each node is no smaller than the key values in its children. A max heap is.
Senem Kumova Metin Spring2009 BINARY TREES && TREE TRAVERSALS Chapter 10 in A Book on C.
1 abstract containers hierarchical (1 to many) graph (many to many) first ith last sequence/linear (1 to 1) set.
CHAPTER 4 TREES §1 Preliminaries 1. Terminology Lineal Tree Pedigree Tree ( binary tree ) 1/17.
CHAPTER 5 PRIORITY QUEUES (HEAPS) §1 ADT Model Objects: A finite ordered list with zero or more elements. Operations:  PriorityQueue Initialize( int.
Binary Trees, Binary Search Trees CMPS 2133 Spring 2008.
1 Chapter 6 Priority Queues (Heaps) General ideas of priority queues (Insert & DeleteMin) Efficient implementation of priority queue Uses of priority queues.
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.
CHAPTER 51 CHAPTER 5 CHAPTER 5 Trees All the programs in this file are selected from Ellis Horowitz, Sartaj Sahni, and Susan Anderson-Freed “Fundamentals.
Lec 15 April 9 Topics: l binary Trees l expression trees Binary Search Trees (Chapter 5 of text)
Binary Tree Properties & Representation. Minimum Number Of Nodes Minimum number of nodes in a binary tree whose height is h. At least one node at each.
1 abstract containers hierarchical (1 to many) graph (many to many) first ith last sequence/linear (1 to 1) set.
CS Data Structures Chapter 5 Trees. Additional Binary Tree Operations (1/7)  Copying Binary Trees  we can modify the postorder traversal algorithm.
Department of Computer Eng. & IT Amirkabir University of Technology (Tehran Polytechnic) Data Structures Lecturer: Abbas Sarraf Trees.
CSC2100B Tutorial 7 Heap Jianye Hao.
Chapter 5 Trees: Outline
More Trees COL 106 Amit Kumar and Shweta Agrawal Most slides courtesy : Douglas Wilhelm Harder, MMath, UWaterloo
Bioinformatics Programming 1 EE, NCKU Tien-Hao Chang (Darby Chang)
§3 Binary Heap 1. Structure Property: 【 Definition 】 A binary tree with n nodes and height h is complete iff its nodes correspond to the nodes numbered.
1 HEAPS & PRIORITY QUEUES Array and Tree implementations.
Foundation of Computing Systems Lecture 6 Trees: Part III.
Data Structures - CSCI 102 Binary Tree In binary trees, each Node can point to two other Nodes and looks something like this: template class BTNode { public:
CS Data Structures Chapter 5 Trees. Chapter 5 Trees: Outline  Introduction  Representation Of Trees  Binary Trees  Binary Tree Traversals 
CS 1031 Tree Traversal Techniques; Heaps Tree Traversal Concept Tree Traversal Techniques: Preorder, Inorder, Postorder Full Trees Almost Complete Trees.
Chapter 5 Binary Trees. Definitions and Properties A binary tree is made up of a finite set of elements called nodes A binary tree is made up of a finite.
Spring 2010CS 2251 Trees Chapter 6. Spring 2010CS 2252 Chapter Objectives Learn to use a tree to represent a hierarchical organization of information.
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.
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. Binary Tree Iterator Similar idea to Linked Lists: Define a class that handles the traversal of the complete tree for us, allowing.
CHAPTER 51 CHAPTER 5 CHAPTER 5 Trees All the programs in this file are selected from Ellis Horowitz, Sartaj Sahni, and Susan Anderson-Freed “Fundamentals.
Starting at Binary Trees
Binary trees -2 Chapter Threaded trees (depth first) Binary trees have a lot of wasted space: the leaf nodes each have 2 null pointers We can.
Preview  Graph  Tree Binary Tree Binary Search Tree Binary Search Tree Property Binary Search Tree functions  In-order walk  Pre-order walk  Post-order.
1 Joe Meehean.  We wanted a data structure that gave us... the smallest item then the next smallest then the next and so on…  This ADT is called a priority.
Data Structures & Algorithm Analysis Muhammad Hussain Mughal Trees. Binary Trees. Reading: Chap.4 ( ) Weiss.
CHAPTER 5 PRIORITY QUEUES (HEAPS) §1 ADT Model Objects: A finite ordered list with zero or more elements. Operations:  PriorityQueue Initialize( int.
CE 221 Data Structures and Algorithms Chapter 6: Priority Queues (Binary Heaps) Text: Read Weiss, §6.1 – 6.3 1Izmir University of Economics.
ADT Binary Search Tree Ellen Walker CPSC 201 Data Structures Hiram College.
Binary Search Trees (BST)
1 Heaps A heap is a binary tree. A heap is best implemented in sequential representation (using an array). Two important uses of heaps are: –(i) efficient.
HEAPS. Review: what are the requirements of the abstract data type: priority queue? Quick removal of item with highest priority (highest or lowest key.
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.
CS 367 Introduction to Data Structures Lecture 8.
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.
Chapter 05 Trees (Part II). Array Representation We can use an array to represent a complete binary tree. Lemma 5.4 ▫If a complete binary tree with.
Yuanming Yu CSCI2100B Data Structures Tutorial 7
EEE2108: Programming for Engineers Chapter 5. Trees
CSCE 3100 Data Structures and Algorithm Analysis
Bohyung Han CSE, POSTECH
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.
CSCI2100 Data Structures Tutorial 7
Chapter 8 – Binary Search Tree
General Trees & Binary Trees
Trees 1: Theory, Models, Generic Heap Algorithms, Priority Queues
CSCE 3110 Data Structures and Algorithm Analysis
General Trees & Binary Trees
Binary Trees, Binary Search Trees
CSCE 3110 Data Structures and Algorithm Analysis
CSCE 3110 Data Structures and Algorithm Analysis
CO4301 – Advanced Games Development Week 4 Binary Search Trees
Binary Trees.
Trees.
Binary Trees, Binary Search Trees
Heaps.
NATURE VIEW OF A TREE leaves branches root. NATURE VIEW OF A TREE leaves branches root.
Presentation transcript:

§3 Binary Tree Traversals —— visit each node exactly once L ::= move left ; R ::= move right ; V ::= visit the node. We will always traverse the left subtree before the right one  LVR 、 LRV 、 VLR Inorder traversal Postorder traversal Preorder traversal 〖 Example 〗 Given a syntax tree of an expression (infix) A + B  C  D + A   D BC Then LVR  A + B  C  D LRV  A B C  D  + VLR  + A   B C D

§3 Binary Tree Traversals  Traversal + A   D BC Recursive Program void inorder (treePointer ptr ) { if ( ptr ) { inorder ( ptr->leftChild ); printf ( “ %d”, ptr->data ); inorder ( ptr->rightChild ); } T p = O( n )  Preorder Traversal void preorder (treePointer ptr ) { if ( ptr ) { printf ( “ %d”, ptr->data ); preorder ( ptr->leftChild ); preorder ( ptr->rightChild ); }  Postorder Traversal void postorder (treePointer ptr ) { if ( ptr ) { postorder ( ptr->leftChild ); postorder ( ptr->rightChild ); printf ( “ %d”, ptr->data ); }  Inorder Traversal

§3 Binary Tree Traversals  Inorder Traversal + A   D BC Algorithm Step 1 : move down along the left path untill NULL is reached; Step 2 : visit\print the parent node; Step 3 : if ( parent has a right child ) { move to the right node; repeat steps 1 to 3; } else { move to the next higher level until the parent of the current node has been visited; repeat steps 2 to 3; } Iterative Program void iterInorder ( treePointer node ) { int top =  1; /* initialize stack */ treePointer stack [ MAX_STACK_SIZE ]; for ( ; ; ) { for ( ; node; node = node->leftChild ) push (&top, node ) ; pop (&top, &node ); if ( !node ) break; printf ( “ %d”, node->data ); node = node->rightChild; } } T p = O( n ) + A   D BC

§3 Binary Tree Traversals  Level Order Traversal —— output nodes in the order as they are numbered Algorithm Step 1 : add the root onto queue; Step 2 : delete \ print one node from queue ; Step 3 : add the left, then the right child of this node onto queue (if it is impossible, then simply continue); Step 4 : Repeat steps 2 to 3 until queue is empty

§3 Binary Tree Traversals Program void levelOrder (treePointer ptr ) { /* level order tree traversal */ int front = rear = 0 ; treePointer queue [ MAX_QUEUE_SIZE ] ; if ( !ptr ) return ; /* empty tree */ addq (front,&rear,ptr ) ; /* push the root onto queue */ for ( ; ; ) { deleteq (&front,rear,&ptr) ; /* pop one node from queue */ if ( ptr ) { printf ( “ %d”, ptr->data ) ; if ( ptr->leftChild ) /* if left child is not NULL */ addq (front,&rear,ptr->leftChild ); /* then push it onto queue */ if ( ptr->rightChild ) /* if right child is not NULL */ addq (front,&rear,ptr->rightChild ); /* then push it onto queue */ } /* end if (ptr) */ else break ; /* if queue is empty, then finish */ } /* end for-loop */ } Can you eliminate it?

§4 Additional Binary Tree Operations  Copying Binary Trees: LRV where V ::= copy ( Program 5.6 on p.212 )  Testing for Equality of Binary Trees: VLR where V ::= test ( Program 5.7 on p.213 )  Create a binary tree  Compute the number of leafs in a binary tree  Compute the depth of a binary tree

 Create a binary tree treePointer Create (treePointer bt){ treePointer bt; char ch; scanf(“%c”,&ch); if (ch == ‘# ') bt = NULL; else { MALLOC(bt, sizeof(struct node), treePointer; bt->data= ch; //create root bt->leftChild = Create(); //create left subtree of root bt->rightChild = Create(); //create right subtree of root } return bt; }//Create

int Leaf(treePointer bt) { if (bt == NULL) return 0; else if ((bt->leftChild == NULL) && (bt->rightChild == NULL)) return 1; else return (Leaf(bt->leftChild)+Leaf(bt->rightChild)); }  Compute the number of leafs in a binary tree

 Compute the depth of a binary tree int Depth(treePointer bt) { int LeftDepth, RightDepth; if (bt == NULL) return 0; else { LeftDepth = Depth(bt->leftChild); RightDepth = Depth(bt->rightChild); return (LeftDepth > RightDepth) ? (LeftDepth + 1) : (RightDepth + 1); }

§5 Threaded Binary Trees Here comes the typical question of mine: Why do we need threaded binary trees? Because I enjoy giving you headaches... Just kidding. Okay, think of a full binary tree with n nodes. How many links are there? 2n links, if each node has only the left and right-child links. How many of them are NULL? n + 1. Can I stand that? Of course not! You got it! Any clue on how to improve the situation? We can replace the null links by “threads” which will make traversals easier. You are such a genius ! Oh well, I wish I’d have really done it Then who should take the credit? They are A. J. Perlis and C. Thornton. Let’s look at the rules first

§5 Threaded Binary Trees Rule 1: If ptr->leftChild is null, replace it with a pointer to the inorder predecessor of ptr. Rule 2: If ptr->rightChild is null, replace it with a pointer to the inorder successor of ptr. Rule 3: There must not be any loose threads. Therefore a threaded binary tree must have a head node of which the left child points to the first node. Structure typedef struct threaded_tree *threaded_ptr; typedef struct threaded_tree { short int leftThread; /* if it is TRUE, then left_child */ threadPointer leftChild; /* is a thread, not a child ptr. */ char data; short int rightThread; /* if it is TRUE, then right_child */ threadPointer rightChild; /* is a thread, not a child ptr. */ }

§5 Threaded Binary Trees + A   D BC 〖 Example 〗 Given the syntax tree of an expression (infix) A + B  C  D FF F + F TATF  F F  FTDT TBTTCT head node

§6 Heaps Priority Queues —— delete the element with the highest \ lowest priority How can we can use efficient data structure to represent the priority queue? Which is the best choice?

§6 Heaps Options of priority queue representation:  Array : Insertion — add one item at the end ~  ( 1 ) Deletion — find the largest \ smallest key ~  ( n ) remove the item and shift array ~ O( n )  Linked List : Insertion — add to the front of the chain ~  ( 1 ) Deletion — find the largest \ smallest key ~  ( n ) remove the item ~  ( 1 )  Ordered Array : Insertion — find the proper position ~ O( n ) shift array and add the item ~ O( n ) Deletion — remove the first \ last item ~  ( 1 )  Ordered Linked List : Insertion — find the proper position ~ O( n ) add the item ~  ( 1 ) Deletion — remove the first \ last item ~  ( 1 )

1. The Heap ADT 【 Definition 】 A max tree is a tree in which the key value in each node is no smaller than the key values in its children (if any). A max heap is a complete binary tree that is also a max tree. 【 Definition 】 A min tree is a tree in which the key value in each node is no larger than the key values in its children (if any). A min heap is a complete binary tree that is also a min tree [1] [2][3] [4] A max heap [1] [2][3] [4] A min heap The largest keyThe smallest key

§6 Heaps structure MaxHeap is objects: A complete binary tree of n > 0 elements organized so that the values in each node is at least as large as those in its children functions: for all heap  MaxHeap, item  Element, and n, max_size  integer MaxHeap Create ( max_size ) ::= creates an empty heap that can hold a maximum of max_size elements. Boolean HeapFull ( heap, n ) ::= if ( n = = max_size ) return TRUE else return FALSE MaxHeap Insert ( heap, item, n ) ::= if ( ! HeapFull ( heap, n ) ) insert item into heap and return the resulting heap else return error

structure MaxHeap is ( continued ) functions: Boolean HeapEmpty ( heap, n ) ::= if ( n > 0 ) return TRUE else return FALSE Element Delete ( heap, n ) ::= if ( ! HeapEmpty ( heap, n ) ) return one instance of the largest element in the heap and remove it from the heap else return error end MaxHeap §6 Heaps Obviously we can use max \ min heaps to represent this kind of queue.

2. Representation of Heap Structure Property: 【 Definition 】 A binary tree with n nodes and height h is complete iff its nodes correspond to the nodes numbered from 1 to n in the perfect binary tree of height h A complete binary tree of height h has between andnodes. 2h2h 2 h+1  1h =  log N   Array Representation : heap [ n + 1 ] ( heap [ 0 ] is not used) D HI E J FG BC A BT 01 A 2 B 3 C 4 D 5 E 6 F 7 G 8 H 9 I 10 J

【 Lemma 】 If a complete binary tree with n nodes is represented sequentially, then for any node with index i, 1  i  n, we have:

Representation #define MAX_ELEMENTS 200 #define HEAP_FULL(n) (n == MAX_ELEMENTS - 1) #define HEAP_EMPTY(n) (!n) typedef struct { int key; /* other fields */ } element; element heap [MAX_ELEMENTS ]; int n = 0;

3. Basic Heap Operations:  Push (Insertion ) [1] [2][3] [4] 18 [5][6]  Sketch of the idea: The only possible position for a new node since a heap must be a complete binary tree. Case 1 : item = < Case 2 : item = > < Case 3 : item = > > 9 §6 Heaps

/* heap[ 0 ] is not used. */ void Push( element item, int *n ) {/* insert intem into a min heap of current size *n */ int i; if ( HEAP_FULL( *n ) ) { fprintf(stderr, “The heap is full.\n" ); return; } i = ++(*n) while ( i != 1 && item.key < heap[i / 2].key) { heap[ i ] = heap [ i / 2]; i /= 2; } heap[ i ] = item; } Percolate up Faster than swap H->Element[ 0 ] is a sentinel that is no larger than the minimum element in the heap. T (N) = O ( log N ) §6 Heaps

 Pop (DeleteMin)  Sketch of the idea: [1] [2][3] [4] 18 [5] The node which must be removed to keep a complete binary tree.  move 18 up to the root 18  find the smaller child of < < 15 Ah! That’s simple -- we only have to delete the root node... And re-arrange the rest of the tree so that it’s still a min heap. T (N) = O ( log N ) §6 Heaps

element Pop( int *n) {/* delete element with the lowest key from the min heap */ int parent, child; element item, temp; if ( HEAP_EMPTY( *n ) ) { fprintf(stderr, “The heap is empty.\n" ); exit(EXIT_FAILURE); } item = heap[1]; temp = heap[(*n)--]; parent = 1; child = 2; while (child <= *n) { if (child heap[child + 1].key) child++; if (temp.key <= heap[child].key) break; heap[parenet] = heap[child]; parent = child; child *= 2; } heap[parent] = temp; return item; } Percolate down What if this condition is omitted?

4. Applications of Priority Queues 〖 Example 〗 Given a list of N elements and an integer k. Find the kth largest element. How many methods can you think of to solve this problem? What are their complexities? §6 Heaps

Homework-3(cont.) P211 #1 , #3 P211 #6. (1). 见书.(2). 画出输入是 Figure5.16 时的栈状态变化示意图. P215 #2 P221 #1 P229 #1, #4