資料結構——二叉樹的結點插入與遍歷
BTree.h:
#ifndef _BTREE_H_
#define _BTREE_H_
//二叉樹的結點資料型別
typedef struct _btreeNode
{
int data;
struct _btreeNode *lchild; //???
struct _btreeNode *rchild; //指向右孩子結點的指標
}BTreeNode;
//建立二叉樹的根結點,即可建立一個二叉樹
typedef struct _btree
{
BTreeNode *root; //指向根結點的指標,代表二叉樹
int count; //統計二叉樹結點的個數
}BTree;
//建立二叉樹,實際就是建立一個 BTree 結點
BTree *creatBTree();
//插入結點
//引數
//b :二叉樹
//data :資料
//pos :路徑 0 代表左 1 代表右 路徑從右往左看6:100 代表路徑 左左右
//count :步數
//flag :掛在結點的左邊還是右邊 0 代表左 1代表 右
int BTree_insert(BTree *b,char data,int pos,int count,int flag);
//前序遍歷
void pre_order(BTreeNode *root);
//中序遍歷
void mid_order(BTreeNode *root);
//後序遍歷
void last_order(BTreeNode *root);
#endif
BTree.c
#include<stdlib.h>
#include"BTree.h"
#include<assert.h>
BTree *creatBTree()
{
//建立二叉樹
BTree *btree=(BTree *)malloc(sizeof(BTree)/sizeof(char));
assert(btree);
//對二叉樹進行初始化
btree->root=NULL;
btree->count=0;
return btree;
}
//插入新節點
int BTree_insert(BTree *b,char data,int pos,int count,int flag)
{
assert(b);
//建立新結點
BTreeNode *node=(BTreeNode *)malloc(sizeof(BTreeNode)/sizeof(char));
assert(node);
//結點初始化
node->data=data;
node->lchild=NULL;
node->rchild=NULL;
int way;//當前要走的路
BTreeNode *current=b->root;
//找插入位置的父結點 pos:2 count=3
while(count!=0)
{
way=pos&1;
pos=pos>>1;
if(way==0) //往左走
current=current->lchild;
else //往右走
current=current->rchild;
count--;
}
if(current==NULL) //剛開始插入時
b->root=node; //新結點成為了新建二叉樹的根結點
else
{
if(flag==0)
{
node->lchild=current->lchild;
current->lchild=node;
}
else
{
node->rchild=current->rchild;
current->rchild=node;
}
}
b->count++; //結點個數加1
return 0;
}
//前序 根左右
void pre_order(BTreeNode *root)
{
if(root==NULL)
return;
printf("%-4c",root->data);
pre_order(root->lchild);
pre_order(root->rchild);
}
//中序 左根右
void mid_order(BTreeNode *root)
{
if(root==NULL)
return;
mid_order(root->lchild);
printf("%-4c",root->data);
mid_order(root->rchild);
}
//後序 左右根
void last_order(BTreeNode *root)
{
if(root==NULL)
return;
last_order(root->lchild);
last_order(root->rchild);
printf("%-4c",root->data);
}
main.c
#include<stdio.h>
#include"BTree.h"
int main()
{
BTree *btree=creatBTree();
int BTree_insert(btree,'A',0,0,0);
int BTree_insert(btree,'B',0,0,0);
int BTree_insert(btree,'C',1,0,1);
int BTree_insert(btree,'D',0,1,0);
int BTree_insert(btree,'E',0,1,1);
int BTree_insert(btree,'F',1,1,0);
int BTree_insert(btree,'G',1,1,1);
int BTree_insert(btree,'H',1,2,1);
pre_order(btree->root);
printf("\n");
mid_order(btree->root);
printf("\n");
last_order(btree->root);
printf("\n");
return 0;
}