简体   繁体   English

二进制搜索树递归显示功能,不确定如何工作?

[英]Binary search tree recursive display function, not sure how it works?

I have a BST and I found this function online, which prints it in the correct order, but I don't understand how. 我有一个BST,并且我在网上找到了此功能,该功能以正确的顺序打印它,但是我不知道如何操作。

void display()
{
    inOrder(root);
}
void inOrder(treeNode* n)
{
   classA foo;
   if (n != NULL)
   {
        inOrder(n->left);
        foo = *n->item;
        cout << foo << endl << endl;
        inOrder(n->right);
    }
 }

I initialize each node's left and right to NULL. 我将每个节点的左右初始化为NULL。 Why does the if statement continue after a NULL pointer is sent in, and where does it continue from? 为什么在发送NULL指针后继续执行if语句,它从何处继续?

Say you have the following BST: 假设您有以下BST:

在此处输入图片说明

When inOrder is called with this BST, inOrder被称为本BST,

Recursion level 0 递归级别0

n points to 8 . n指向8 So you enter the block: 因此,您输入了块:

    inOrder(n->left);
    foo = *n->item;
    cout << foo << endl << endl;
    inOrder(n->right);

inOrder is called using n->left as argument, which is node 3 . 使用n->left作为参数(节点3 )调用inOrder

Recursion level 1 递归级别1

n points to 3 . n指向3 So you enter the same code block. 因此,您输入相同的代码块。

inOrder is called using n->left as argument, which is node 1 . 使用n->left作为参数(节点1 )调用inOrder

Recursion level 2 递归级别2

n points to 1 . n指向1 So you enter the same code block. 因此,您输入相同的代码块。

inOrder is called using n->left as argument, which is NULL . 使用n->left作为参数调用inOrder ,即NULL

Recursion level 3 递归级别3

n points to NULL . n指向NULL So you do not enter the above code block. 因此,您无需输入上面的代码块。 You simply return from the function. 您只需从函数中返回即可。 Now are back in the next statement in the previous recursion level. 现在返回上一个递归级别的下一个语句。

Recursion level 2 递归级别2

The following lines are executed: 执行以下行:

    foo = *n->item;
    cout << foo << endl << endl;
    inOrder(n->right);

You print 1 . 您打印1 Then, inOrder is called using n->right as argument, which is NULL . 然后,使用n->right作为参数调用inOrder ,该参数为NULL

Recursion level 3 递归级别3

n points to NULL . n指向NULL So you do not enter the above code block. 因此,您无需输入上面的代码块。 You simply return from the function. 您只需从函数中返回即可。 Now are back in the next statement in the previous recursion level. 现在返回上一个递归级别的下一个语句。

Recursion level 2 递归级别2

There are no more lines to execute. 没有更多要执行的行。 The function simply returns to previous recursion level. 该函数仅返回到先前的递归级别。

Recursion level 1 递归级别1

The following lines are executed: 执行以下行:

    foo = *n->item;
    cout << foo << endl << endl;
    inOrder(n->right);

You print 3 . 您打印3 Then, inOrder is called using n->right as argument, which is node 6 . 然后,使用n->right作为参数(节点6 )调用inOrder

You can now follow this step by step all the way. 现在,您可以逐步执行此步骤。 The end result is that you will end up printing the numbers in the following order. 最终结果是您将最终按照以下顺序打印数字。

1
3
4
6
7
8
10
13
14

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

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