typedef struct Node{ //结构体类型
int data;
struct Node *leftchild;
struct Node *rightchild;
}Node;
//-------------------------------------------------------- 初始化 -----------------------------------------------------------------------//
void InitBinaryTree(Node**root,int elem){ //初始化
*root=(Node*)malloc(sizeof(Node));
if(!(*root)){
printf("Memory allocation for root failed.\n");
return;
}
(*root)->data=elem;
(*root)->leftchild=NULL;
(*root)->rightchild=NULL;
}
//------------------ 插入结点,若插入数据小于父结点,插入左子树;若大于父结点,插入右子树 ---------------//
void InsertNode(Node *root,int elem){
Node *newnode=NULL;
Node *p=root,*last_p=NULL;
newnode=(Node*)malloc(sizeof(Node));
if(!newnode){
printf("Memory allocation for newnode failed.\n");
return;
}
newnode->data=elem;
newnode->leftchild=NULL;
newnode->rightchild=NULL;
while(NULL!=p){ //循环让头指针指向它要插入结点的位置
last_p=p;
if(newnode->data < p->data){
p=p->leftchild;
}
else if(newnode->data > p->data){
p=p->rightchild;
}
else{
printf("Node to be inserted has existed.\n");
free(newnode);
return;
}
}
p=last_p;
if(newnode->data < p->data){
p->leftchild=newnode;
}
else{
p->rightchild=newnode;
}
}
//----------------------------------------------打印结点-------------------------------------------//
void visit(Node *p){
printf("%d\n",p->data);
}
//--------------------------------递归的前序、中序、后序遍历-------------------------------//
void MidTreverse(Node *root){
if(root != NULL){
MidTreverse(root->leftchild);
visit(root);
MidTreverse(root->rightchild);
}
}
void PreTreverse(Node *root){
if(root != NULL){
visit(root);
PreTreverse(root->leftchild);
PreTreverse(root->rightchild);
}
}
void BeTreverse(Node *p){
if(p!=NULL){
BeTreverse(p->leftchild);
BeTreverse(p->rightchild);
visit(p);
}
}
//---------------------------------------------------主函数--------------------------------------//
int main(){
Node *head=NULL;
InitBinaryTree(&head, 4);
InsertNode(head, 2);
InsertNode(head, 1);
InsertNode(head, 3);
InsertNode(head, 6);
InsertNode(head, 5);
InsertNode(head, 7);
// MidTreverse(head);
PreTreverse(head);
// BeTreverse(head);
printf("Hello world!\n");
return 0;
}