Presentation is loading. Please wait.

Presentation is loading. Please wait.

§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.

Similar presentations


Presentation on theme: "§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."— Presentation transcript:

1

2 §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 §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

4 §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

5 §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. 2 45 3 67 1 1 1 23 2 45 3 67 4 567

6 §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?

7 §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

8  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

9 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

10  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); }

11 §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

12 §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. */ }

13 §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

14 §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?

15 §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 )

16 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. 9 6 5 3 [1] [2][3] [4] A max heap 10 20 50 83 [1] [2][3] [4] A min heap The largest keyThe smallest key

17 §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

18 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.

19 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. 4 89 5 1011 6 1213 7 1415 23 1 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 111213

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

21 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;

22 3. Basic Heap Operations:  Push (Insertion ) 10 12 15 20 [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 = 21 21 2021 < Case 2 : item = 17 17 2017 > 20 1017 < Case 3 : item = 9 209 > 9 109 > 9 §6 Heaps

23 /* 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

24  Pop (DeleteMin)  Sketch of the idea: 10 12 15 20 [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 18 1218 < 12 1518 < 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

25 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?

26 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

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


Download ppt "§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."

Similar presentations


Ads by Google