c++ - 在屏幕上打印整个二叉树
问题描述
我想将数字存储在二叉树中,以 0 退出,然后按升序输出数字。我看到的大多数答案都是在树中搜索,而少数涵盖这个确切主题的答案使用了我不理解的方法。我相信树本身是正确创建的,但是输出函数有问题。我哪里做错了?
#include <iostream>
#include <stdio.h>
using namespace std;
struct thing {
short num;
short howmany = 0;
thing* right;
thing* left;
};
void insert(thing* akt, short x) {
if (akt == NULL) {
akt = new thing;
akt->left = NULL;
akt->right = NULL;
akt->num = x;
akt->howmany++;
}
else if (akt->num == x) akt->howmany++;
else if (akt->num > x) return insert(akt->right, x);
else return insert(akt->left, x);
}
void output(thing* root) {
thing* akt;
do {
akt = root;
while(akt->left!=NULL) akt=akt->left;
if(akt->right!=NULL) return output(akt->right);
cout << akt->num << " " << akt->howmany << "times\n";
akt = NULL;
} while (root != NULL);
}
int main() {
thing* root = new thing;
short x;
cout << "number: ";
cin >> x;
do {
insert(root, x);
cout << "number: ";
cin >> x;
} while (x != 0);
cout << endl;
output(root);
return 0;
}
解决方案
有多个错误。第一个插入函数按值传递指针,因此从未修改过根。
还修正了输出功能。
#include <iostream>
#include <stdio.h>
using namespace std;
struct thing {
short num;
short howmany = 0;
thing* right;
thing* left;
};
void insert(thing* &akt, short x) {
if (akt == NULL) {
akt = new thing;
akt->left = NULL;
akt->right = NULL;
akt->num = x;
akt->howmany++;
}
else if (akt->num == x) akt->howmany++;
else if (akt->num > x) return insert(akt->left, x);
else return insert(akt->right, x);
}
void output(thing* root) {
thing* akt = root;
if(akt == NULL)
return;
output(akt->left);
cout << akt->num << " " << akt->howmany << " times\n";
output(akt->right);
}
int main() {
thing* root = NULL;
short x;
cout << "number: ";
cin >> x;
do {
insert(root, x);
cout << "number: ";
cin >> x;
} while (x != 0);
cout << endl;
output(root);
return 0;
}`
推荐阅读
- html - 如何让我的 css 链接到我的 html fie?
- python - 带有日期滑块和播放小部件/动画的 iPyWidget?
- xslt - 使用 Heat 工具收集 Wix 后无法修改 Directoryref/Directory 元素的 Name 属性值
- javascript - 从 html 表创建嵌套对象 JSON?
- html - 使用 powershell 对齐电子邮件正文中的列
- java - 常用方法的Spring异常处理
- r - 不在 RStudio 中时使用 R 代码重新启动 R 会话?
- c++ - 从数组创建图标
- asp.net-core - Wix Installer ASP.NET Core 单独解决方案
- python - pyspark:Spark 2.3 中的arrays_zip 等效项