BST c++ 中的指针帮助

Pointer help in BST c++

本文关键字:指针 帮助 c++ BST      更新时间:2023-10-16

我的BST有一个名为pTree的根。它由以下人员声明:

KnightTree* tree;

现在我需要编写一个带有指向根(在本例中为"树")的新指针的函数,如果我使用 pTree=pTree->pLeftChild; 或 pTree=pTree->pRightChild;在调用下面的函数之前,我声明:

KnightTree* treeroot=tree;

然后我调用该函数:

ReadNLR(tree,treeroot);

函数是这样的:

void ReadNLR(KnightTree*&tree,KnightTree* treeroot)
{
    if(tree !=NULL)
    {
        cout<<tree->key<<" is at the depth of "<<NodeDepth(treeroot,tree)<<endl;
        cout<<treeroot->key<<endl;
        ReadNLR(tree->pLeftChild,treeroot);
        ReadNLR(tree->pRightChild,treeroot);
    }
}

我的想法是进行NLR读取,每个节点读取都将打印出其深度。但是我在这里遇到的问题是树根就像树的副本一样,它们是相同的,因此深度始终为 1(从节点到根的距离加 1)。如何从初始树根声明即使树更改也不会更改的树根?谢谢,对不起我的英语!

乍一看,您的代码看起来不错,只是树参数没有理由引用指针。我的猜测是NodeDepth有问题.建议是随时跟踪级别,而不是重新计算它。您的函数对树执行深度优先扫描,如下所示:

void ReadNLR(KnightTree* tree, int level)
{
    if (tree == NULL)
        return;
    cout << tree->key << " is at the depth of " << level;
    ReadNLR(tree->pLeftChild, level + 1);
    ReadNLR(tree->pRightChild, level + 1);
}

您可以通过调用带有 root0 作为参数的 ReadNLR 来开始打印过程。

您还可以使用队列逐级打印树 - 如果您仍然需要帮助,我会尽快发布。