简体   繁体   English

二进制搜索树排序

[英]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. 我有以下示例代码可以工作..但无法理解这是如何工作的..它启动,如果数据库中没有记录,那么b = 0并返回。 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? 如果b存在,那么它会进入左边节点并再次调用该函数,直到b-> left == NULL ..我能正确理解吗? 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. 您可能想要使用大约8个节点的树来尝试它。

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. 它将一直遍历到左下角并且命中0.然后它返回一个节点并在return语句之后继续该节点的代码。 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. 鉴于display_ordered_email应该按顺序递归打印节点,你可以问自己何时应该打印b 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). 答案是b它已经访问和打印后应打印a (左侧),但在其将访问和打印c (右侧)。

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. 这正是你的例行程序的结构。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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