2017-07-29 41 views
-1

我是一名新手程序员。我在二叉搜索树中创建了一个插入和预遍历程序。但问题是前序遍历函数不打印任何东西。当我尝试遍历树时,什么都不打印。我试图解决这个问题,但不幸的是,我没能解决这个问题...请帮助...预先遍历树时没有输出

#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; 
    } 
    } 
    } 

回答

0

那是因为你传递root的价值,你的功能,而不是参考。你insert定义应该是这样的:

void insert(struct node*& root,int k) 

你实际上做的是传递给函数COPYroot,所以其真正的价值是永远不会更新。