二叉查找树
2009-12-08 19:58
92 查看
[实验内容]
1、二叉查找树的建立和中序输出
2、二叉查找树的查找
【实验测试数据】
输入数据:33,88,22,55,90,11,66,99
查找:77是否存在,99是否存在
二叉查找树性质:
1 若它的左子树非空,则左子树上所有结点的值均小于它的根结点的值;
2 若它的右子树非空,则右子树上所有结点的值均大于它的根节点的值;
3 它的左、右子树也分别为二叉查找树
源程序:
1、二叉查找树的建立和中序输出
2、二叉查找树的查找
【实验测试数据】
输入数据:33,88,22,55,90,11,66,99
查找:77是否存在,99是否存在
二叉查找树性质:
1 若它的左子树非空,则左子树上所有结点的值均小于它的根结点的值;
2 若它的右子树非空,则右子树上所有结点的值均大于它的根节点的值;
3 它的左、右子树也分别为二叉查找树
源程序:
]#include <stdio.h> #include <stdlib.h> #include <malloc.h> typedef struct BSTNode { int key; struct BSTNode *lchild,*rchild; }BSTNode, *BSTree; void InsertBST(BSTree *bst, int key); void CreateBST(BSTree *bst); void InOrder(BSTree *root) ; void InsertBST(BSTree *bst, int key) { BSTree s; if (*bst == NULL) { s=(BSTree)malloc(sizeof(BSTNode)); s-> key=key; s->lchild=NULL; s->rchild=NULL; *bst=s; } else if (key < (*bst)->key) InsertBST(&((*bst)->lchild), key); else if (key > (*bst)->key) InsertBST(&((*bst)->rchild), key); } void CreateBST(BSTree *bst) { int key; *bst=NULL; scanf("%d", &key); while (key!=0) { InsertBST(bst, key); scanf("%d", &key); } } void InOrder(BSTree *root) { if (*root!=NULL) { InOrder(&(*root) ->lchild); printf("%3d",((*root) ->key)); InOrder(&(*root) ->rchild); } } void SearchBST(BSTree *bst, int x) { if (*bst==NULL) printf("%d is not found",x); else if(x==(*bst)->key) { printf("%d is found",x); exit(0); } else if (x < (*bst)->key) SearchBST(&((*bst)->lchild), x); else if (x > (*bst)->key) SearchBST(&((*bst)->rchild), x); } void main() { BSTree BST; int x,y; CreateBST(&BST); InOrder(&BST); printf("\nWhich number?\n"); scanf("%d%d",&x,&y); SearchBST(&BST,x); printf("\n"); SearchBST(&BST,y); }
相关文章推荐
- 查找树ADT--二叉查找树
- 二叉查找树的c++实现
- 二叉查找树,红黑树,AVL树,B~/B+树(B-tree),伸展树——优缺点及比较
- 二叉查找树
- 二叉查找树转变为有序双向链表
- 二叉查找树——懒惰删除
- 二叉查找树(java版本)
- 95 - 验证二叉查找树
- 二叉查找树(三)之 Java的实现
- 数据结构实战java实现二叉查找树
- 【LeetCode】Validate Binary Search Tree 验证二叉查找树 - Medium+
- 4 张 GIF 图帮助你理解二叉查找树
- Golang以OO的方式实现二叉查找树
- 非递归实现二叉查找树插入操作
- 二叉查找树的构建及遍历
- 二叉查找树
- 二叉查找树(BST)
- lintcode---将二叉查找树转换成双链表
- 算法-二叉查找树-插入节点
- 算法-二叉查找树-迭代器