生成二叉排序树
来源:互联网 发布:初中语文软件苹果版 编辑:程序博客网 时间:2024/06/04 18:53
构建原则: 左子树<根<右子树
//#--------------------------------
//#插入法生成二叉排序树//#--------------------------------
#include<stdio.h>
typedef struct BSTnode {
int data;
struct BSTnode *lchild, *rchild;
}*BSTnode;
void insert(BSTnode * root, int value) { //#插入函数,核心
if(! *root) {
(*root)=(BSTnode)malloc(sizeof(struct BSTnode)) ;
(*root)->data=value;
}
else {
if(value < (*root)->data) {
insert( &((*root)->lchild),value);
}
else {
insert( &((*root)->rchild),value);
}
}
}
BSTnode createBST(int arr[],int n) { // #生成BST
int tmp;
int i=0;
BSTnode root=NULL;
while (i < n) {
tmp=arr[i++];
insert(&root,tmp); //#传入&root的原因是:root的值会被改变
}
return root;
}
void MIDprint(BSTnode root) { // #中序遍历
if(root) {
MIDprint(root->lchild);
printf("%d\t",root->data);
MIDprint(root->rchild);
}
}
void PREprint(BSTnode root) { //#前序遍历
if(root) {
printf("%d\t",root->data);
PREprint(root->lchild);
PREprint(root->rchild);
}
}
int main() {
int arr[]={1,4,5,7,9,8,6};
BSTnode root=createBST(arr,7);
MIDprint(root); //#根据前序遍历和中序遍历可以知道生成的BST是什么样子
printf("\n");
PREprint(root);
printf("\n");
return 0;
}
0 0
- 生成二叉排序树
- 二叉排序树生成查找
- 二叉排序树
- 二叉排序树
- 二叉排序树
- 二叉排序树
- 二叉排序树
- 二叉排序树
- 二叉排序树
- 二叉排序树
- 二叉排序树
- 二叉排序树
- 二叉排序树
- 二叉排序树
- 二叉排序树
- 二叉排序树
- 二叉排序树
- 二叉排序树
- 《C语言及程序设计》程序阅读——数组与指针
- Android开发学习笔记之图片数据互转
- 如何在Android的TextView中显示带html的文本
- iOS、mac开源项目及库
- 以下命令在循环语句中时要在结尾处要加分号
- 生成二叉排序树
- Theme.AppCompat.Light的解决方法
- MySQL全文索引Match Against与Like比较
- CURL中curl_setopt的中文含义
- HDU3527 SPY 【集合】
- jdk、jre、jvm区别
- Image<TColor, TDepth>与Image
- 理解SerDes 之二
- 映射法数据深度复制