Jump to content

Can someone help explain this recursive function

- - - - -

  • Please log in to reply
4 replies to this topic

#1
flodywan

flodywan

    Newbie

  • Members
  • Pip
  • 9 posts
Can someone help to explain how this recursion works? It's just a few lines of code but I'm not sure how the program is stepping through it so that it works.

In a binary tree, to display all the data I've been using this code:
int tree::display_tree(node*& root)

{

  if (root)

  {

    display_music(root->left);

    root->music_node::display();

    display_music(root->right);

  }

  

  return 0;

}


#2
omega

omega

    Newbie

  • Members
  • PipPip
  • 16 posts
first of all, can you post the definition of the "node",

and,

if (root)
 {
     display_music(root->left);
     root->music_node::display();
     display_music(root->right);
 }

from analyzing this code i figured out that:

1. global function void display_music( node *& n )

2. node has a data member: node * right
3. node has a data member: node * left

4. node has composed structure named music_node with static member display()

#3
flodywan

flodywan

    Newbie

  • Members
  • Pip
  • 9 posts
Sorry I didn't mean to make it confusing with my specific class/structs. I'm just talking about generic tree traversal using recursion. I found a snippet of code online that shows how to print all the data for any tree. How does this work?:

void printTree(struct node* node) 
{
  if (node == NULL) return;

  printTree(node->left);
  printf("%d ", node->data);
  printTree(node->right);
} 


#4
omega

omega

    Newbie

  • Members
  • PipPip
  • 16 posts
now your code is correct and clear as the sun !

this is DEEPENING TRAVERSAL known as IN-ORDER TRAVERSE !!

FIRST {LEFT} THEN {PARENT} THEN {RIGHT}

EXAMPLE:
[B][COLOR=Red]TREE:[/COLOR][/B]
               ([COLOR=Red]A[/COLOR])
               /  \
             ([COLOR=Red]B[/COLOR])  ([COLOR=Red]C[/COLOR])
             / \  / \
           ([COLOR=Red]D[/COLOR])([COLOR=Red]E[/COLOR])([COLOR=Red]F[/COLOR])([COLOR=Red]G[/COLOR])

[B][COLOR=Blue]OUTPUT:[/COLOR][/B]  [COLOR=Blue]*[/COLOR] [COLOR=Red]D [COLOR=Blue]*[/COLOR] B [COLOR=Blue]*[/COLOR] E [COLOR=Blue]*[/COLOR] A [COLOR=Blue]*[/COLOR] F [COLOR=Blue]*[/COLOR] C [COLOR=Blue]*[/COLOR] G [/COLOR][COLOR=Blue]*[/COLOR]

[B]NOTE:[/B] [COLOR=Blue]*[/COLOR] [U]SYMBOLIZE CALLS WITH PARAMETER[/U][COLOR=Red] "[COLOR=Blue]NULL[/COLOR]"[/COLOR]


#5
flodywan

flodywan

    Newbie

  • Members
  • Pip
  • 9 posts
Ahhhh wow I can't believe I didn't see that before. I kept thinking that the recursive function call was just gonna skip over the printf. Thanks so much for your help!




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users