本程序主要实现二叉树的建树,排序输入的数据,查找数据的功能。
建树:1、输入采用数组方式,方便扩展;
2、反复使用tree_insert来建树,tree_insert主要是解决在哪里加结点和新加结点和老结点的关系;
排序:直接使用中序遍历,得到从小到大的输出
查找:二叉查找树存在的最大价值在于快速的查找,实现见代码
#include<stdio.h>
#include<iostream>
#include<string.h>
#include<algorithm>
using namespace std;
typedef struct BiTreeNode{
int date;
struct BiTreeNode *lchild, *rchild, *parent;
}BiTreeNode,*BiTree;
BiTree root;
int a[100]={0};
void tree_insert(BiTree bt, int key)
{
BiTree x,y,z;//y is father, x is son, z is temp
z=(BiTreeNode*)malloc(sizeof(BiTreeNode));//ask room
x=bt;
while(x!=NULL)//find the location for inserting node
{
y=x;//record the father of inserting location
if(key>x->date)
x=x->rchild;
else
x=x->lchild;
}
x=z;//put the real room in the inserting location
x->date=key;
x->parent=y;
if(y==NULL)root=x;//if it is a empty tree,
//transfer the real room location to root(global varible)
if(y==NULL)//if it is a empty tree, the root has no parent, do nothing
{
return;//x->date=key;
}
else {
//tell the father that whether the child is
//his right child or left child
if(key < y->date)
y->lchild=x;
else
y->rchild=x;
}
}
int tree_search(BiTree x,int key)
{
if (x==NULL) return 0;//can't find key
if (x->date==key) return 1;//find key
if (key < (x->date))//
tree_search(x->lchild,key);
else
tree_search(x->rchild,key);
}
void tree_inorder_walk(BiTree x)
{
if (x!=NULL)
{
tree_inorder_walk(x->lchild);
printf("%d ",x->date);
tree_inorder_walk(x->rchild);
}
}
int main()
{
int i,n;
root=NULL;
//input the information of the BST
printf("how many nodes in this tree:");
scanf("%d",&n);
printf("input the key of nodes:");
for(i=1;i<=n;i++)
scanf("%d",&a[i]);//12,5,8,18
//insert
for(i=1;i<=n;i++)
tree_insert(root,a[i]);
//check if there is a established tree
printf("\ndescribe the tree:\n");
printf("root is %d\n",root->date);
//sort the nums
printf("\nsort:");
tree_inorder_walk(root);
//search node
printf("\n\nsearch node:\n");
printf("can we find 5 in the BST: %d \n",tree_search(root,5));
printf("can we find 6 in the BST: %d \n",tree_search(root,6));
return 0;
}