二叉搜索树:无输出
Binary Search Tree : no output
我正在为我的作业做一个二叉搜索树,但它没有显示inorder, preorder和 poststor 的任何输出。即使我在inorder
preorder
和postorder
函数中使用cout
,但它没有给我任何输出。我觉得错误是在createBst
功能,但我不确定…请帮帮我吧提前谢谢你:-)
#include <iostream>
using namespace std;
struct node
{
int info;
struct node *left;
struct node *right;
}*r;
struct node * createBst(struct node *r, int val)
{
if (r == NULL)
{
r = new node;
r->info = val;
r->left = NULL;
r->right = NULL;
}
else if (val <= r->info)
{
// cout<<r->left<<" ";
r->left = createBst(r->left, val);
}
else
{
r->right = createBst(r->right, val);
cout << r->right << " ";
}
return r;
}
void inOrder(struct node *r)
{
if (r != NULL)
{
inOrder(r->left);
cout << r->info;
inOrder(r->right);
}
}
void preOrder(struct node *r)
{
if (r != NULL)
{
cout << r->info;
preOrder(r->left);
preOrder(r->right);
}
}
void postOrder(struct node *r)
{
if (r != NULL)
{
postOrder(r->left);
postOrder(r->right);
cout << r->info;
}
}
int main()
{
r = NULL;
int n, val;
cout << "Enter the number of element" << endl;
cin >> n;
for (int i = 0; i < n; i++)
{
cin >> val;
//cout<<"check";
createBst(r, val);
}
cout << "Inorder" << endl;
//cout<<r->info<<endl;
inOrder(r);
cout << endl;
cout << "PreOrder" << endl;
preOrder(r);
cout << endl;
cout << "PostOrder" << endl;
postOrder(r);
cout << endl;
}
In
createBst(r, val);
OP没有收到更新后的r
,因为
r
struct node * createBst(struct node *r, int val)
和
不是同一个r
struct node
{
int info;
struct node *left;
struct node *right;
}*r;
可以使用
修复r = createBst(r, val);
或通过更改
struct node * createBst(struct node *r, int val)
通过引用获取指针。
struct node * createBst(struct node * & r, int val)
离题了,OP设置了一些可笑的编译器和逻辑错误,将r
作为全局变量,然后在其函数中广泛使用变量名称r
作为自动变量。一个错别字加上一个清晰的"变量r未定义"消息会让整个过程变得更加混乱。
因为不解释如何解决这个问题使我成为一个自私的混蛋,只是在这里嘲笑"the noobz",在这里失去*r
:
struct node
{
int info;
struct node *left;
struct node *right;
}*r;
和声明
node * r;
在main
的顶部。在main
结束时,我强烈建议遍历BST和delete
所有节点,以防止内存泄漏。我是一个虐待成性的折磨者,所以我不解释这个。
相关文章:
- 有根的二进制搜索树.保留与其父级的链接
- 正在尝试重载二进制搜索树分配运算符
- 使用C++创建特殊的二叉搜索树
- 在递归二叉搜索树中搜索
- 在二叉搜索树中插入时出现分段错误
- C++二叉搜索树模板从函数返回节点
- 我可以在没有堆栈的情况下在二叉搜索树中实现迭代器吗?
- 在二叉搜索树C++中计算平均值
- 在字符串的二叉搜索树中搜索子字符串 - C++
- 在二叉搜索树中插入新元素
- 如何打印在二叉搜索树中找到的数据?
- 查找存储在二叉搜索树的所有非叶子中的数据总和?(返回整数的独立递归函数
- 这是一个二叉搜索树吗?黑客排名问题
- 二叉搜索树 - 实现"search"函数
- 输出二叉搜索树中的叶节点数
- 在C++中实现二叉搜索树,搜索不起作用.尝试打印节点的元素会导致输出崩溃
- 二进制搜索树的输出不正确
- 输出在二叉搜索树的有序遍历中略有偏差
- 二进制搜索树最佳拟合算法:输出不正确
- 二叉搜索树:无输出