260 likes | 339 Views
+. A. . . D. B. C. §3 Binary Tree Traversals —— visit each node exactly once. L ::= move left ; R ::= move right ; V ::= visit the node.
E N D
+ A D B C §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 Then LVR A + B C D LRV A B C D + VLR +A B C D
§3 Binary Tree Traversals Recursive Program void inorder (treePointer ptr ) { if ( ptr ) { inorder ( ptr->leftChild ); printf ( “ %d”, ptr->data ); inorder ( ptr->rightChild ); } } void preorder (treePointer ptr ) { if ( ptr ) { printf ( “ %d”, ptr->data ); preorder ( ptr->leftChild ); preorder ( ptr->rightChild ); } } void postorder (treePointer ptr ) { if ( ptr ) { postorder ( ptr->leftChild ); postorder ( ptr->rightChild ); printf ( “ %d”, ptr->data ); } } + A D B C Traversal Inorder Traversal Preorder Traversal Postorder Traversal Tp = O( n )
§3 Binary Tree Traversals 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; } } + + A A D D B B C C Inorder Traversal Tp = O( n )
§3 Binary Tree Traversals 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. 1 2 3 4 6 5 7 Level Order Traversal —— output nodes in the order as they are numbered 1 2 3 4 5 6 7 1 2 3 4 5 6 7
§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: VLRwhere 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
Compute the number of leafs in a binary tree 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 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 Let’s look at the rules first 2n links, if each node has only the left and right-child links. 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? Any clue on how to improve the situation? We can replace the null links by “threads” which will make traversals easier. Then who should take the credit? They are A. J. Perlis and C. Thornton. You are such a genius ! n + 1. Oh well, I wish I’d have really done it Of course not! How many of them are NULL? You got it! Can I stand that?
§5 Threaded Binary Trees 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. */ } 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.
§5 Threaded Binary Trees head node F F F + F T A T F F F F T D T + T B T T C T A D B C 〖Example〗 Given the syntax tree of an expression (infix) A + B C D
§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 )
The smallest key The largest key 10 9 [1] [1] [2] [2] 6 20 [3] [3] 83 3 5 50 [4] [4] 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. A max heap A min heap
§6 Heaps structure MaxHeapis 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, andn, max_size integer MaxHeap Create ( max_size ) ::= creates an empty heap that can hold a maximum of max_sizeelements. Boolean HeapFull ( heap, n ) ::=if( n = = max_size)returnTRUE else returnFALSE MaxHeap Insert( heap, item, n ) ::=if( !HeapFull ( heap, n ) )insert item into heap and return the resulting heap else returnerror
§6 Heaps structure MaxHeapis ( continued ) functions: Boolean HeapEmpty ( heap, n ) ::=if( n > 0)returnTRUE else returnFALSE Element Delete( heap, n ) ::=if( !HeapEmpty ( heap, n ) )returnone instance of the largest element in the heap and remove it from the heap else returnerror endMaxHeap Obviously we can use max \ min heaps to represent this kind of queue.
1 A C B 3 2 A complete binary tree of height h has between and nodes. h = log N 6 5 7 4 D H 14 10 8 12 11 15 9 I 13 BT 0 1 2 3 4 5 6 A B C D E F 7 8 9 10 11 12 13 G H I J E F G J 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. 2h 2h+1 1 Array Representation : heap [ n + 1 ] ( heap [ 0 ] is not used)
【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;
§6 Heaps 20 20 20 10 10 > < < > > 9 17 21 9 17 10 [1] [2] 12 [3] 20 15 18 [4] [5] [6] 3. Basic Heap Operations: Push (Insertion ) Sketch of the idea: The only possible position for a new node since a heap must be a complete binary tree. 9 17 10 9 17 21 20 Case 1 : item = 21 Case 2 : item = 17 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; } H->Element[ 0 ] is a sentinel that is no larger than the minimum element in the heap. Percolate up Faster than swap T (N) = O ( log N )
§6 Heaps 10 [1] [2] 12 [3] 20 15 18 [4] [5] < < 12 15 18 18 Pop (DeleteMin) Ah! That’s simple -- we only have to delete the root node ... Sketch of the idea: And re-arrange the rest of the tree so that it’s still a min heap. The node which must be removed to keep a complete binary tree. move 18 up to the root 12 18 15 18 find the smaller child of 18 18 T (N) = O ( log N )
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 < *n && heap[child].key > 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; } What if this condition is omitted? Percolate down
§6 Heaps 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?
Homework-3(cont.) • P211 #1,#3 • P211 #6. (1). 见书.(2).画出输入是Figure5.16时的栈状态变化示意图. • P215 #2 • P221 #1 • P229 #1, #4