二叉搜索树(BST)
Binary Search Tree(BST)
大家好,我犯了逻辑错误,但我没有发现错误。
谢谢:))
我的算法#include <iostream> //iostream
using namespace std;
struct node{
struct node *left;
struct node *right;
int data;
};
void add(node *p,int sayi){
if(p==NULL){
p=new node();
p->data=sayi;
p->left=NULL;
p->right=NULL;
}
else if(p->data>=sayi){
add(p->left,sayi);
}
else {
add(p->right,sayi);
}
}
void postorder(node *p)
{
if(p!=NULL)
{
if(p->left!=NULL)
postorder(p->left);
if(p->right!=NULL)
postorder(p->right);
cout<< p->data<<endl;
}
else{
cout<<"hata"<<endl;
}
}
void main(){
struct node *k=NULL ;
int sayi=0;
while(sayi!=-1){
cout<<"Bir sayi giriniz...";
cin>>sayi;
add(k,sayi);
}
postorder(k);
system("pause");
}
按值传递struct node *k
。当你在一个函数中改变它时(比如在add
中),它只改变了局部副本(在一个函数中),所以你得到一个NULL
指针。通过引用或指针传递:
void add(node* &p,int sayi)
{
...
}
struct node *k = 0;
...
add(k);
或
void add(node** p,int sayi)
{
...
}
struct node *k = 0;
...
add(&k);
您的数据结构应该有一个根节点来跟踪。您需要将这个根节点引用传递给postorder()
和add()
函数调用。这里k
看起来是您的根节点。在外部声明k
,以便可以在函数add()
内部访问它。
#include <iostream> //iostream
using namespace std;
struct node{
struct node *left;
struct node *right;
int data;
};
struct node *k=NULL; //ROOT NODE
void add(node *p,int sayi){
if(p==NULL){
p=new node();
p->data=sayi;
p->left=NULL;
p->right=NULL;
if(k==NULL)
k=p; //When the first node is created, we assign it to root, i.e, k
}
else if(p->data>=sayi){
add(p->left,sayi);
}
else {
add(p->right,sayi);
}
}
void postorder(node *p)
{
if(p!=NULL)
{
if(p->left!=NULL)
postorder(p->left);
if(p->right!=NULL)
postorder(p->right);
cout<< p->data<<endl;
}
else{
cout<<"hata"<<endl;
}
}
void main(){
int sayi=0;
while(sayi!=-1){
cout<<"Bir sayi giriniz...";
cin>>sayi;
add(k,sayi);
}
postorder(k);
system("pause");
}
试着这样修改你的代码:
#include <iostream> //iostream
using namespace std;
struct node{
struct node *left;
struct node *right;
int data;
};
node* add(node *p,int sayi){
if(p==NULL){
p=new node();
p->data=sayi;
p->left=NULL;
p->right=NULL;
return p;
}
else if(p->data>=sayi){
p->left=add(p->left,sayi);
}
else {
p->left=add(p->right,sayi);
}
return p;
}
void postorder(node *p)
{
if(p!=NULL)
{
if(p->left!=NULL)
postorder(p->left);
if(p->right!=NULL)
postorder(p->right);
cout<< p->data<<endl;
}
else{
cout<<"hata"<<endl;
}
}
int main(){
struct node *k=NULL ;
int sayi=0;
while(sayi!=-1){
cout<<"Bir sayi giriniz...";
cin>>sayi;
k=add(k,sayi);
}
postorder(k);
}
相关文章:
- 有根的二进制搜索树.保留与其父级的链接
- 正在尝试重载二进制搜索树分配运算符
- 使用C++创建特殊的二叉搜索树
- 在递归二叉搜索树中搜索
- 在二叉搜索树中插入时出现分段错误
- C++二叉搜索树模板从函数返回节点
- 我可以在没有堆栈的情况下在二叉搜索树中实现迭代器吗?
- 在二叉搜索树C++中计算平均值
- 在字符串的二叉搜索树中搜索子字符串 - C++
- 在二叉搜索树中插入新元素
- 如何打印在二叉搜索树中找到的数据?
- 查找存储在二叉搜索树的所有非叶子中的数据总和?(返回整数的独立递归函数
- 这是一个二叉搜索树吗?黑客排名问题
- 二叉搜索树 - 实现"search"函数
- 二叉搜索树 (BST) 返回左子被视为函数,不理解
- 平衡二叉搜索树 (BST)
- 测试二叉搜索树(BST)的遍历
- c++迭代插入到二叉搜索树BST
- 二叉搜索树- c++ BST补充说明更改
- 二叉搜索树(BST)