Another tree example Phylogenetic tree Patient 1 Plan Clone Phylogeny B C RFTA16 Om1 • Tree ADT A E ROv1 SBwl D G • Tree recursion F H I • Tree traversal ROv2 SBwlE4 Search and score n Search runtime O(2 ) Pass message from leafs ROv3 LFTB4 to root recursively ROv4 LOvB2 Traverse tree is post-order!! ROvA4 ApC1 1
Ordered binary tree ADT Empty node = NULL pointer BEE • Ordered binary tree node can have left and right children EMU ANT • Recursively: either empty or o o a root with left and right children which are ordered CAT DOG o o o o binary trees template < class T> Tree ADT class tree{ • Insert node public : ... • Remove node private : struct Node{ • Traverse We could add T data; a parent pointer Node * left; to Node to traverse Node * right;}; up the tree Like head for Node * root; linked list ...}; 2
Counting empty trees How many empty trees hang off a binary tree with n nodes? Each node has 2 children => 2n nodes real or empty n real nodes only root not child => n-1 real nodes A So there are n+1 empty nodes B C Proof by induction: F G D E Let E(n) be # empty nodes in tree w/ n nodes E(0) = 1 Empty tree has single empty node J K H I n = #nodes in T E(n)=E(n )+E(n ) L R L L L n = #nodes in T R R n + n = n - 1 L R E(n) = (n + 1) + (n + 1) by I.H. L R = (n + n ) + 2 R L = (n - 1) + 2 = n + 1 3
Tree traversal Pay c at each of n nodes cout << n->data << endl; 10 Pay b at each of inOrderTraversal(Node * n){ n+1 empty nodes if (n != NULL){ 5 15 c pre c c 2 9 20 inOrderTraversal(n->left); b b b c 7 17 30 in b b In order: inOrderTraversal(n->right); 2, 5, 9, 7, 10, 15, 17, 20, 30 post Right Left Pre Runtime O(n) 10, 5, 2, 9, 7, 15, 20, 17, 30 }} T(n)=cn+b(n+1) Post T(n)=T(n ) + T(n )+ c R L 2, 7, 9, 5, 17, 30, 20, 15, 10 T(0)= b n + n = n - 1 L R by I.H. T(n)=b(n + n + 2) + c(n + n )+c 4 R L L R
Eulerian tree tour a c b Pre Post e d f In i h j T T L R Pre Post In a a a b c b c b c e e e d f d f d f i h i h i h j j j d,b,f,a,c,i,j,e,h d,f,b,j,i,h,e,c,a a,b,d,f,c,e,i,j,h 5
Applications • Tree copy • Tree delete Node * treeCopy(Node * n){ if(n!=NULL){ return new Node(n->data, treeCopy(n->left), treeCopy(n->right)) } } void treeDelete(Node * n){ if (n == NULL) return; treeDelete(n->left); treeDelete(n->right); delete n; } 6
Level (depth) order Output: a, b, c, d, f, e, i, h, j, a 0 void printLevelOrder(){ c b 1 if (root == NULL) return ; Queue<Node *> Q; e 2 d f Q.enqueue(root); while (!Q.empty()){ i h 3 Node * n = Q.dequeue(); j 4 if (n == NULL) continue; cout << n->data << ","; Q Q.enqueue(n->left); a e d c b f Q.enqueue(n->right); 2 2 2 1 1 0 } How to show correct? Loop invariant } 7
Recommend
More recommend