3

I need to define a main function that reads integers and prints them back in ascending order.

    For example, if the input contains

       12
       4
       19
       6

   the program should output

       4
       6
       12
       19

I need to use trees to do this however. I'm given the use of two functions insertavl, and deleteavlat my disposal. Their defintions are like so... http://ideone.com/8dwlU basically when deleteavl is called it deletes the node, and rebalances the tree accordingly ... If interested thier structures are in: http://ideone.com/QjlGe.

I've gotten this so far:

int main (void) {
   int number;
   struct node *t = NULL;
   while (1 == scanf("%d",&number)) {     
          t = insertavl(t, number);              
   }
   while (t != NULL){
      printf("%d\n",t->data);
      t = deleteavl(t, t->data);    
   }    
}

But this doesn't print them in ascending order. Any suggestions would be helpful? thanks in advance!

glglgl
  • 89,107
  • 13
  • 149
  • 217
Thatdude1
  • 905
  • 5
  • 18
  • 31

1 Answers1

4

Hint: in-order traversal on a BST is iterating the elements in ascending order.

Since an AVL Tree is a specific implementation of a BST, it also applies here.

EDIT: Explanation - why is this property of in-order traversal on a BST correct?

In in-order trvaersal, you access [print] each node after you accessed all the nodes in the left subtree. Since in a BST the root is bigger then all the nodes in the left subtree, it is what we wanted.

Also, in in-order traversal, you access each node before accessing all elements in the right sub-tree, and again, since it is a BST - this is exactly what we want.

(*)Note: This is not a formal proof, just an intuitive explanation why it is true.

amit
  • 175,853
  • 27
  • 231
  • 333
  • really? all i need to do after i make the tree just use the inorder function to arrange it in ascending order ? – Thatdude1 Mar 04 '12 at 18:50
  • @Beginnernato: Have a look at the link to wikipedia I attached, it has pseudo-code of an in-order traversal function, it is pretty easy in my opinion. Just implement it and run it, it should work [unless there is a bug in some other part of the program] – amit Mar 04 '12 at 18:50
  • @Beginnernato: I added an explanation for this property in BST. So yes, all you need to do is print elements in in-order traversal – amit Mar 04 '12 at 18:54
  • i realized with inorder, i wont use deleteavl which i need to use im preety shure ... to free the nodes ? – Thatdude1 Mar 04 '12 at 18:59
  • @Beginnernato: yes, to avoid memory leaks, you will need to delete all nodes before you `return` from `main()` – amit Mar 04 '12 at 19:01
  • that was really fast for your response, I'm guessin our prof's should've taught us about transversal... thanks for ur help amit :) – Thatdude1 Mar 04 '12 at 19:07