二叉树的建立与插入和遍历

#include<stdio.h>
#include<stdlib.h>




typedef struct name{
int Data;
struct name *left;
struct name *right;
}Node,*PNode;




typedef PNode BinTree;
PNode CreateTree();
PNode Insert(PNode BST,int x);
void PreorderTraversal(BinTree BT);
void InorderTraversal(BinTree BT);


int main(void)
{
PNode T;
PNode BST;
int Data;
int flag=0,flag2=0;
T=CreateTree();
while(Data!=-1)
{

scanf("%d",&Data);
if(flag2==0)
{
T->Data=Data;
flag2=1;
continue;
}
if(Data==-1)
{
break;
}
if(flag==0)
{
BST=Insert(T,Data);
}
flag=1;
Insert(T ,Data);
}
// printf("%d  ",T);
// printf("%d \n",BST);
printf(" PreorderTraversal \n");
PreorderTraversal(BST);
printf(" InorderTraversal \n");
InorderTraversal(BST);

return 0;
}
PNode CreateTree()
{
PNode Y;
Y=(PNode)malloc(sizeof(Node));
Y->left=NULL;
Y->right=NULL;
//printf("%d",Y->Data);
return Y;
}
PNode Insert(PNode BST,int x)
{
if(!BST){
BST=(BinTree)malloc(sizeof(Node));
BST->Data=x;
BST->left=BST->right=NULL;
}
else
{
if(x<BST->Data)
BST->left=Insert(BST->left,x);
else if(x>BST->Data)
BST->right=Insert(BST->right,x);
}
return BST;
}
void PreorderTraversal(BinTree BT)
{
if(BT)
{
printf("%d ",BT->Data);
PreorderTraversal(BT->left);
PreorderTraversal(BT->right);
}
}
void InorderTraversal(BinTree BT)
{
if(BT)
{
InorderTraversal(BT->left);
InorderTraversal(BT->right);
printf("%d ",BT->Data);
}
}

猜你喜欢

转载自blog.csdn.net/weixin_42383680/article/details/80582805