您的位置:首页 > 其它

10---------二叉树的算法的简单应用

2017-12-20 21:24 537 查看
二叉排序树的构建和查找算法

求二叉树的宽度算法

求二叉树的深度算法

二叉树的构建算法

*

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

/**
* 二叉排序树的构建和查找算法
* 求二叉树的宽度算法
* 求二叉树的深度算法
* 二叉树的构建算法
*
*/

typedef struct BTNode{
int data;
struct BTNode * lchild;
struct BTNode * rchild;
}BTNode;

//平衡二叉树的搜索算法
BTNode * searchTBTNode(BTNode * bt,int key){
if(bt == NULL){
return NULL;
}else{
if(bt->data == key) return bt;
else if(key < bt->data) return searchTBTNode(bt->lchild,key);
else return searchTBTNode(bt->rchild,key);
}
}

//构建一个新的结点作为二叉排序树的结点
int createTBT(BTNode ** bt,int e){
if((*bt) == NULL){
(*bt) = (BTNode *)malloc(sizeof(BTNode));
(*bt)->lchild = (*bt)->rchild = NULL;
(*bt)->data = e;
return 1;
}else{
if(e == (*bt)->data){
return 0;
}else if(e < (*bt)->data){
return createTBT(&(*bt)->lchild,e);
}else{
return createTBT(&(*bt)->rchild,e);
}
}
}

//二叉树排序树的构建算法
BTNode * createTBTTree(int arr[],int n){    //数组中不存在相同大小的数据
int i;
BTNode * bt;
for(i=0;i<n;i++){
createTBT(&bt,arr[i]);
}
return bt;
}

//二叉树的深度算法
int getDeep(BTNode * root){
int ld,rd;
if(root == NULL){
return 0;
}
ld = getDeep(root->lchild);
rd = getDeep(root->rchild);
return
bdb7
(ld>rd?rd:rd)+1;
}

//二叉树宽度的算法,需要定义一个辅助的结构体,用来标记当前层号,然后构造一个队列,因为要用到二叉树的层序遍历
typedef struct ST{
BTNode * bt;
int no; //用来标记当前层号
}ST;

#define maxsize 100

int getBoard(BTNode * root){
ST st[maxsize];
int front,rear;
front = 0; rear = 0;
BTNode * s;
int currentNum;
//先让根结点入队
if(root != NULL){
++rear;
st[rear].bt = root;
st[rear].no = 1;
while(rear != front){   //这里用到的是大数组顺序队列
++ front;   //表示出队,但不释放元素
currentNum = st[front].no;
s = st[front].bt;
if(s->lchild){
++rear;
st[rear].bt = s->lchild;
st[rear].no = currentNum + 1;
}else if(s->rchild){
++rear;
st[rear].bt = s->rchild;
st[rear].no = currentNum + 1;
}
}
//已经按层将二叉树的每个结点存放到了一个数组中
int max=0,i,j,n;
for(i=1;i<=currentNum;i++){
n = 0;
for(j=1;j<=rear;j++){
if(st[j].no == i){
n++;
}
}
if(max<n){
max = n;
}
}
return max;
}else{
return 0;
}
}

//二叉树的构建算法
BTNode * createBTNode(){
BTNode * bt = (BTNode *)malloc(sizeof(BTNode));
int e;
scanf("%d",&e);
if(e == 0){
bt->lchild = NULL;
bt->rchild = NULL;
return NULL;
}
bt->lchild = createBTNode();
bt->rchild = createBTNode();
return bt;
}

int main(){
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: