C++ 预排序遍历树时没有输出

C++ 预排序遍历树时没有输出,c++,c++14,C++,C++14,我是一个新手程序员。我在二叉搜索树中做了一个关于插入和前序遍历的程序。但问题是,预序遍历函数没有打印任何内容。当我试图穿过这棵树时,什么也没印出来。我试图解决这个问题,但不幸的是,我没能解决它。。。请帮忙 #include<iostream> #include<stdio.h> using namespace std; struct node { int data; struct node* left; struct node* r

我是一个新手程序员。我在二叉搜索树中做了一个关于插入和前序遍历的程序。但问题是,预序遍历函数没有打印任何内容。当我试图穿过这棵树时,什么也没印出来。我试图解决这个问题,但不幸的是,我没能解决它。。。请帮忙

 #include<iostream>
 #include<stdio.h>
 using namespace std;
 struct node
 {
     int data;
     struct node* left;
     struct node* right;
 };

 void insert(struct node * root,int k)
{
struct node *n,*pre;
n=(struct node *)malloc(sizeof(struct node));
n->left=NULL;
n->right=NULL;
n->data=k;
if(root==NULL)
 root=n;
else
 {
 pre=root;
 while(pre!=NULL)
 {
    if(k<pre->data)
    {  
        if(pre->left==NULL)
          {
           pre->left=n;
          }
        pre=pre->left;
    }
    else if(k>pre->data)
    {
        if(pre->right==NULL)
          {
             pre->right=n;
          }
        pre=pre->right;
    }

 }

  }
 }
 void traversal(struct node * root)
 {
 if(root!=NULL)
 {
    cout<<root->data<<endl;
    traversal(root->left);
    traversal(root->right);
 }

 }

 int main()
 {
   struct node *root=NULL;
   int i,data;
   while(1)
   {
     cout<<"1.Enter into tree"<<endl;
     cout<<"2.traverse"<<endl;
     cout<<"3.exit"<<endl;
     cin>>i;
     switch(i)
     {
        case 1:cout<<"input a number:";
               cin>>data;
               insert(root,data);
               break;
        case 2:cout<<"The elements of the tree:"<<endl;
               traversal(root);
               break;
        case 3:cout<<"Exiting.... || bye!";
               exit(0);      
               break; 
    }
   }
  }
#包括
#包括
使用名称空间std;
结构节点
{
int数据;
结构节点*左;
结构节点*右;
};
空插入(结构节点*根,int k)
{
结构节点*n,*pre;
n=(结构节点*)malloc(sizeof(结构节点));
n->left=NULL;
n->right=NULL;
n->data=k;
if(root==NULL)
根=n;
其他的
{
pre=根;
while(pre!=NULL)
{
if(kdata)
{  
如果(预->左==NULL)
{
pre->left=n;
}
pre=pre->left;
}
否则如果(k>预->数据)
{
如果(预->右==NULL)
{
前->右=n;
}
pre=pre->right;
}
}
}
}
无效遍历(结构节点*根)
{
if(root!=NULL)
{

cout这是因为您是按值向函数传递
,而不是按引用传递。您的
插入
定义应如下所示:

void insert(struct node*& root,int k)
实际上,您要做的是将函数aCOPY传递到
root
,因此它的实际值永远不会更新