主题:二叉树的创建及遍历问题,试了很久,高手帮帮手
#include<stdio.h>
#include<math.h>
#include<iostream.h>
#include<malloc.h>
typedef struct BinTree
{
int data;
struct BinTree*left,*right;
}tree;
tree* insert(tree*root,int x)//建二叉树
{
tree*p;
if(root==NULL)//若为根结点
{
p=(tree*)malloc(sizeof(tree));
p->data=x;
p->left=NULL;
p->right=NULL;
return(p);
}
else if(x<root->data)
root->left=insert(root->left,x);
else
root->right=insert(root->right,x);
return root;
}
void middle(tree*root)//中序遍历
{
middle(root->left);
cout<<root->data;
middle(root->right);
}
void main()
{
int x;
tree* root=NULL;
cin>>x;
while(x!=-1)//-1时结束
{
root=insert(root,x);
cin>>x;
}
middle(root);
}
运行时出错,为什么?[em10]
#include<math.h>
#include<iostream.h>
#include<malloc.h>
typedef struct BinTree
{
int data;
struct BinTree*left,*right;
}tree;
tree* insert(tree*root,int x)//建二叉树
{
tree*p;
if(root==NULL)//若为根结点
{
p=(tree*)malloc(sizeof(tree));
p->data=x;
p->left=NULL;
p->right=NULL;
return(p);
}
else if(x<root->data)
root->left=insert(root->left,x);
else
root->right=insert(root->right,x);
return root;
}
void middle(tree*root)//中序遍历
{
middle(root->left);
cout<<root->data;
middle(root->right);
}
void main()
{
int x;
tree* root=NULL;
cin>>x;
while(x!=-1)//-1时结束
{
root=insert(root,x);
cin>>x;
}
middle(root);
}
运行时出错,为什么?[em10]