[英]Binary Search Tree displaying nodes recursively
我的显示函数处理二进制搜索树时出现问题。 我遇到的主要问题是让count变量在递归函数中正确递增,以便可以按升序对节点进行编号。
将计数作为全局变量会起作用吗?
这是该函数的代码:
(p指向树的根,计数最初设置为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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.