创建二叉排序树,先序遍历,中序遍历,判断是否存在关键点
这是所要创建的二叉排序树,a[10] = {4, 5, 2, 1, 0, 9, 3, 7, 6, 8},请先在草稿纸上画出图形,再看程序
代码实现:
#include <stdio.h>
#include <stdlib.h>
typedef struct BTNode{
int key,cout;
struct BTNode *lchild;
struct BTNode *rchild;
}BTNode;
//创建二叉排序树
bool BSTInsert(BTNode *&bt,int x){
if(bt==NULL){
bt=(BTNode*)malloc(sizeof(BTNode));
bt->key=x;
bt->lchild=bt->rchild=NULL;
return true;
}
if(x==bt->key)
return false;
if(x>bt->key)
return BSTInsert(bt->rchild,x);
else
return BSTInsert(bt->lchild,x);
}
//先序遍历
void PreOrderTraverse(BTNode *bt){
if(bt){
printf("%d ",bt->key);
PreOrderTraverse(bt->lchild);
PreOrderTraverse(bt->rchild);
}
}//中序遍历
void InOrderTraverse(BTNode *bt){
if(bt){
InOrderTraverse(bt->lchild);
printf("%d "