二叉查找树的构造算法

今天来写一下二叉查找树的构造算法

二叉查找树:二叉查找树的的特点是所有节点的值要大于其左节点的值,小于其右节点的值。。。

因此我们在构造二叉查找树的查找算法的时候总是用要查找的数来和节点的值做一个比较,如果节点的值大于要查找的数,那么继续查找其左节点,反之则继续查找器右节点,一直到查找到你要的数。

本算法包括计算树的高度,树的叶子节点的数目,树的所有节点的数目,以及树的输出。

1.头文件

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

2.结构

 

1 typedef struct node
2 {
3     int data;
4     struct node *lchild, *rchild;
5 }btnode,*BTnode;

 

3.构造树

BTnode Create()
{
    int a;
    BTnode root;
    scanf("%d", &a);
//如果你输入的数为0,那么就停止构建你所构建的分支
if (a == 0) return NULL; else { root = (BTnode)malloc(sizeof(btnode));  //分配内存地址 root->data = a;  //赋值 root->lchild = Create();  //利用递归算法构造左分支和右分支 root->rchild = Create(); } return root;  //最后返回这个二叉树 }

4.计算树的高度

 1 int btdepth(BTnode bt)
 2 {
 3     int ldepth, rdepth;
 4     if (bt == NULL)  //如果树为空,则返回0
 5         return 0;
 6     else
 7     {
 8         ldepth = btdepth(bt->lchild);  //分别利用递归求左分支的高度和右分支的高度,最后最高的那个分支加上根节点则是树的高度
 9         rdepth = btdepth(bt->rchild);
10         return (ldepth > rdepth ? ldepth + 1 : rdepth + 1);
11     }
12 }

5.计算树的节点数

1 int ncount(BTnode bt)
2 {
3     if (bt == NULL)
4         return 0;
5     else
6         return (ncount(bt->lchild) + ncount(bt->rchild) + 1);  //不断的用递归求节点数,最后求的左分支的节点数加上右分支的节点数再加上根节点则是树的所有的节点
7 }

6.计算树的叶子节点数

1 int lcount(BTnode bt)
2 {
3     if (bt == NULL)
4         return 0;
5     else if (bt->lchild == NULL&&bt->rchild == NULL)  //如果节点的子节点为空那么就返回1,即表示只有一个节点,也就是一个叶子节点
6         return 1;
7     else 
8         return (lcount(bt->lchild) + lcount(bt->rchild));  //利用递归求得满足子节点为空的节点数
9 }

7.查找算法

 1 void search(BTnode bt,int key)
 2 {
 3     while (bt != NULL)
 4     {
 5         if (bt->data == key)  查找成功,则退出循环
 6         {
 7             printf("查找成功!!\n");
 8             break;
 9         }
10         else if (bt->data > key)  //要查找的数小于节点值,则继续查找左节点
11             bt = bt->lchild;
12         else  //反之查找右节点
13             bt = bt->rchild;
14     }
15     if (bt == NULL)
16         printf("没有找到!\n");
17 }

8.输出算法

1 void print(BTnode bt)  //利用中序遍历输出数的节点值
2 {
3     if (bt != NULL)
4     {
5         printf("%d", bt->data);
6         print(bt->lchild);
7         print(bt->rchild);
8     }
9 }

9.主函数

 1 void main()
 2 {
 3     int key;
 4     BTnode root;
 5     root = Create();
 6     printf("输出二叉树为:\n");
 7     print(root);
 8     printf("\n");
 9     printf("树的高度为:%d\n", btdepth(root));
10     printf("树的节点数为:%d\n", ncount(root));
11     printf("树的叶子节点数为:%d\n", lcount(root));
12     printf("请输入你要查找的数:");
13     scanf("%d", &key);
14     search(root, key);
15 }

 更多博客请访问:http://www.livekeys.club/

posted @ 2017-06-05 10:29  livekeys  阅读(5861)  评论(0编辑  收藏  举报