定义结构体
#include <stdio.h>
#include <stdlib.h>
typedef struct Btree{
int val;
struct Btree* lNode;
struct Btree* rNode;
}Btree;
创建结点
Btree* createNode(int data){
Btree* newNode = (Btree*)malloc(sizeof(Btree));
if(!newNode){
printf("开辟内存失败\n");
exit(1);
}
newNode->val = data;
newNode->lNode = NULL;
newNode->rNode = NULL;
return newNode;
}
插入
左插
void insertLNode(Btree* root ,int data){
//结点不存在
if(!root){
printf("插入错误,该结点不存在!\n");
return;
}
//结点左子树不空
if(root->lNode!=NULL){
printf("插入失败,该节点已有左子树!\n");
return;
}
//左子树空
Btree* newNode = createNode(data);
root->lNode = newNode;
}
右插
void insertRNode(Btree* root ,int data){
//结点不存在
if(!root){
printf("插入错误,该结点不存在!\n");
return;
}
//结点右子树不空
if(root->rNode!=NULL){
printf("插入失败,该节点已有右子树!\n");
return;
}
//右子树空
Btree* newNode = createNode(data);
root->rNode = newNode;
}
递归遍历
先序遍历
//先序遍历
void printTreeF(Btree* root){
if(root!=NULL){
printf("%d ",root->val);
printTreeF(root->lNode);
printTreeF(root->rNode);
}
}
中序遍历
//中序遍历
void printTreeM(Btree* root){
if(root!=NULL){
printTreeM(root->lNode);
printf("%d ",root->val);
printTreeM(root->rNode);
}
}
后续遍历
//后序遍历
void printTreeE(Btree* root){
if(root!=NULL){
printTreeE(root->lNode);
printTreeE(root->rNode);
printf("%d ",root->val);
}
}
测试
int main(){
Btree* root = createNode(6);
insertLNode(root,3);
insertRNode(root,4);
insertLNode(root->lNode,5);
insertRNode(root->lNode,1);
insertLNode(root->rNode,2);
printTreeF(root);
printf("\n");
printTreeM(root);
printf("\n");
printTreeE(root);
return 0;
}
完整代码
#include <stdio.h>
#include <stdlib.h>
typedef struct Btree{
int val;
struct Btree* lNode;
struct Btree* rNode;
}Btree;
Btree* createNode(int data){
Btree* newNode = (Btree*)malloc(sizeof(Btree));
if(!newNode){
printf("开辟内存失败\n");
exit(1);
}
newNode->val = data;
newNode->lNode = NULL;
newNode->rNode = NULL;
return newNode;
}
void insertLNode(Btree* root ,int data){
//结点不存在
if(!root){
printf("插入错误,该结点不存在!\n");
return;
}
//结点左子树不空
if(root->lNode!=NULL){
printf("插入失败,该节点已有左子树!\n");
return;
}
//左子树空
Btree* newNode = createNode(data);
root->lNode = newNode;
}
void insertRNode(Btree* root ,int data){
//结点不存在
if(!root){
printf("插入错误,该结点不存在!\n");
return;
}
//结点右子树不空
if(root->rNode!=NULL){
printf("插入失败,该节点已有右子树!\n");
return;
}
//左子树空
Btree* newNode = createNode(data);
root->rNode = newNode;
}
//先序遍历
void printTreeF(Btree* root){
if(root!=NULL){
printf("%d ",root->val);
printTreeF(root->lNode);
printTreeF(root->rNode);
}
}
//中序遍历
void printTreeM(Btree* root){
if(root!=NULL){
printTreeM(root->lNode);
printf("%d ",root->val);
printTreeM(root->rNode);
}
}
//后序遍历
void printTreeE(Btree* root){
if(root!=NULL){
printTreeE(root->lNode);
printTreeE(root->rNode);
printf("%d ",root->val);
}
}
int main(){
Btree* root = createNode(6);
insertLNode(root,3);
insertRNode(root,4);
insertLNode(root->lNode,5);
insertRNode(root->lNode,1);
insertLNode(root->rNode,2);
printTreeF(root);
printf("\n");
printTreeM(root);
printf("\n");
printTreeE(root);
return 0;
}