二叉搜索树递归显示节点

Binary Search Tree displaying nodes recursively

本文关键字:显示 节点 递归 搜索树      更新时间:2023-10-16

我在处理二叉搜索树的显示函数时遇到问题。我遇到的主要问题是让 count 变量在递归函数中正确递增,以便我可以按升序对节点进行编号。

使计数成为全局变量会起作用吗?

下面是该函数的代码:

(p 指向树的根,count 最初设置为 1)

void displayAscend(nodePtr p, int count)
   {
      if (p->left != NULL)
         displayAscend(p->left, count);
      cout << count << ". " << p->acctNum << endl;
      count++;
      if (p->right != NULL)
         displayAscend(p->right, count);
   }

通过引用 int& 传递计数。

void displayAscend(nodePtr p, int& count)

更改

displayAscend(p->left, count);

displayAscend(p->left, count+1);

与包含 p->right 的行相同.

我怀疑你想要这样的东西:

size_t displayAscend(nodePtr p, int count)
{
   size_t additional_count = 0;
   if (p->left != NULL)
      additional_count += displayAscend(p->left, count + additional_count);
   cout << count + additional_count << ". " << p->acctNum << endl;
   additional_count++;
   if (p->right != NULL)
      additional_count += displayAscend(p->right, count + additional_count);
   return additional_count;
}

如果您愿意,可以使用int代替size_t

原因是每个递归调用

都必须向其调用方返回一个计数,否则调用方无法知道递归调用已计数多少。 当然,最外面的调用者如果不感兴趣,可以丢弃计数。

正如另一个答案所观察到的那样,通过引用传递是另一种方法,尽管不是我的首选方法。 (我个人更喜欢使用明确的指针来实现策略。

你问count全局变量是否有效。 答案是,是的,它可以满足你有限练习的有限目的,但它代表了糟糕的编程实践。 毕竟,如果你有几棵树,每棵树都有自己的数量呢?

更新:感谢@JerryCoffin指出我的代码中的前一个错误。 我已经在上面修复了它。 更重要的是,我已经用以下内容对其进行了测试:

#include <vector>
#include <iostream>
using std::cout;
using std::endl;
struct node {
   node *left;
   node *right;
   int acctNum;
};
typedef node *nodePtr;
size_t displayAscend(nodePtr p, int count)
{
   size_t additional_count = 0;
   if (p->left != NULL)
      additional_count += displayAscend(p->left, count + additional_count);
   cout << count + additional_count << ". " << p->acctNum << endl;
   additional_count++;
   if (p->right != NULL)
      additional_count += displayAscend(p->right, count + additional_count);
   return additional_count;
}
int main() {
   node head;
   node n1;
   node n2;
   node n11;
   node n21;
   node n22;
   head.left  = &n1;
   head.right = &n2;
   n1  .left  = &n11;
   n1  .right = 0;
   n2  .left  = &n21;
   n2  .right = &n22;
   n11 .left  = 0;
   n11 .right = 0;
   n21 .left  = 0;
   n21 .right = 0;
   n22 .left  = 0;
   n22 .right = 0;
   n11 .acctNum = 100;
   n1  .acctNum = 202;
   head.acctNum = 300;
   n21 .acctNum = 400;
   n2  .acctNum = 500;
   n22 .acctNum = 600;
   displayAscend(&head, 0);
}

输出为

0. 100
1. 202
2. 300
3. 400
4. 500
5. 600

所以,它有效。

您必须通过引用传递 count 变量。

void displayAscend(nodePtr p, int & count)
   {
      if (p->left != NULL)
         displayAscend(p->left, count);
      cout << count << ". " << p->acctNum << endl;
      count++;
      if (p->right != NULL)
         displayAscend(p->right, count);
   }