assignment5

2 in this problem we continue our study of binary

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: t s ( " should d isplay 2 0 ,30 " ) ; d i s p l a y ( np ) ; /∗ t e s t d e l n o d e ∗/ h ead=d e l n o d e ( head , np ) ; p u t s ( " should d isplay 1 0 ,30 " ) ; d i s p l a y ( head ) ; n p=f i n d ( head , 1 0 ) ; h ead=d e l n o d e ( head , np ) ; p u t s ( " should d isplay 3 0 " ) ; d i s p l a y ( head ) ; / ∗ c l e a n up ∗ / f r e e l i s t ( head ) ; return 0 ; } 5 Problem 5.2 In this problem, we continue our study of binary trees. Let the nodes in the tree have the following structure s truct t node { i n t d ata ; s truct t node ∗ l e f t ; s truct t node ∗ r i g h t ; }; Use the template in Lec06 (slides 41) to add elements to the list. (a) Write the function struct tnode∗ talloc(int data) that allocates a new node with the given data. (b) Complete the function addnode() by filling in the missing section. Insert elements 3, 1, 0, 2, 8, 6, 5, 9 in the same order. (c) Write function void preorder(struct tnode∗ root) to display the elements using pre-order traver­ sal. (d) Write function void inorder(struct tnode∗ root) to display the elements using in-order traversal. Note that the elements are sorted. (e) Write function int deltree (struct tnode∗ root) to delete all the elements of the tree. The function must return the number of nodes deleted. Make sure not to use any pointer after it has been freed. (Hint: use post-order traversal). (f) Write test code to illustrate the working of each of the above functions. All the code and sample outputs should be submitted. 6 Answer: Here’s one possible implementation: #include < s t d i o . h> #include < s t d l i b . h> s truct t node { i n t d ata ; s truct t node ∗ l e f t ; s truct t node ∗ r i g h t ; }; /∗ @function @ desc @param @ return talloc a l l o c a t e s a new n ode d ata [ IN ] p a y l o a d p o i n t e r t o t h e new n ode o r NULL o n f a i l u r e ∗/ s truct t node ∗ t a l l o c ( i n t d ata ) { struct t node ∗ p =( struct t node ∗ ) m a l l o c ( s i z e o f ( s truct t node ) ) ; i f ( p !=NULL) { p−>data=data ; p−> l e f t =p−> r i g h t =NULL; } return p ; } /∗ @function @ desc @param @returns a ddnode i n s e r t s n ode i n t o t h e t r e e d ata [ IN ] d ata t o b e i n s e r t e d u pdated r o o t t o t h e t r e e ∗/ s truct t node ∗ a ddnode ( s truct t node ∗ r o o t , i n t d ata ) { i f ( r o o t==NULL) { struct t node ∗ n ode=t a l l o c ( data ) ; return...
View Full Document

This document was uploaded on 03/17/2014 for the course EECS 6.087 at MIT.

Ask a homework question - tutors are online