简体   繁体   中英

Binary search tree Sorting

i want to sort some data with the help of a binary search tree, that i have already created. I have the following example code that works.. But can't understand how this works.. It starts and if there is no record in the database then b=0 and returns. This is clear. If b exists, then it goes to the left node and calls the function again and again until b->left ==NULL.. Do i get it correctly? But when does it print the data, since from what i get when it runs the function it doesnt print, but starts again from the top of the function..

void display_ordered_email(struct BST_node *b)
{
    if (b==0)           
        return;            
    display_ordered_email(b->left);
    printf("Name    : %s\n", b->data->name);
    printf("Address : %s\n", b->data->address);
    printf("Email   : %s\n", b->data->email);
    printf("\n");
    display_ordered_email(b->right);
}

Is this inorder traversal or other method?

This is your pre-order traversal using recursion. Once you are done with the left subtree, it prints the root of that subtree followed by right subtree. You may want to try it out with a tree of about 8 nodes.

It will traverse all the way to the bottom left and hit 0. then it moves back one node and continues the code for that node after the return statement. This means it will print that code and then try it for the right node. If there is no right node it just returns otherwise it prints the right node. Then if both are done it will back up one level and print everything there then check that right branch for any branches it may have.

It is quite confusing at first but if you draw it out it becomes a lot easier to understand.

Consider this simple tree.

   b
  / \
 a   c

Given that display_ordered_email is supposed to recursively print the nodes in order, you can ask yourself when b should be printed. The answer is that b should be printed after it has visited and printed a (the left side), but before it will visit and print c (the right side).

void display_ordered_email(struct BST_node *b)
{
    if (b==0)           
        return;            
    display_ordered_email(b->left);
    /* ... print the node */
    display_ordered_email(b->right);
}

which is exactly how your routine is structured.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM