设为首页 加入收藏

TOP

二叉查找树(一)
2013-12-05 12:46:43 来源: 作者: 【 】 浏览:1292
Tags:查找

  在网上找了好久,也没有找到自己想要的二叉查找树实现。根据算法导论上的思路方法,写了一个c语言版的二叉查找树实现。

  /*******************************************

  二叉查找树,支持的操作包括:SERACH、MINIMUM、

  MAXIMUM、PREDECESSOR、SUCCESSOR、INSERT、DELETE.

  定理:对于一个高度为h的二叉查找树,操作SERACH、MINIMUM、

  MAXIMUM、PREDECESSOR、SUCCESSOR的运行时间均为O(h)

  *******************************************/

  日期: 2013-11-13

  ============================================*/

  #include <stdio.h>

  #include <stdlib.h>

  #include <string.h>

  #define WORDLEN 16

  //定义一个节点,除了存放key值外,还包含了一个data字符数组用于存放一个单词

  struct node{

  int key;

  char data[WORDLEN];

  struct node *parent;

  struct node *left;

  struct node *right;

  };

  typedef struct node * tree;

  /*============================================

  树的中序遍历

  INORDER_TREE_WALK(x)

  if x!=NIL

  then INORDER_TREE_WALK(left[x])

  print key[x]

  INORDER_TREE_WALK(left[x])

  ============================================*/

  void inorder_tree_walk(tree T)

  {

  if(T!=NULL){

  inorder_tree_walk(T->left);

  printf("key:%d   words:%s\n",T->key,T->data);

  inorder_tree_walk(T->right);

  }

  }

  /*============================================

  树的搜索,返回含有关键字k的结点

  TREE_SEARCH(x,k) //递归版本

  if x=NIL or k =key[x]

  then return x

  if k<key[x]

  then return TREE_SEARCH(left[x],k)

  else return TREE_SEARCH(right[x],k)

  TREE_SEARCH(x,k) //非递归版本

  while x!=NIL and k!= key[x]

  do if k<key[x]

  then x <-- left[x]

  else x <-- right[x]

  return x

  ============================================*/

  //递归版本

  struct node* tree_search(tree T,int k)

  {

  if(T==NULL || k == T->key)

  return T;

  if(k < T->key)

  return tree_search(T->left,k);

  else

  return tree_search(T->right,k);

  }

  //非递归版本

  struct node* tree_search1(tree T,int k)

  {

  while(T!=NULL && T->key!=k)

  if(k < T->key)

  T=T->left;

  else

  T=T->right;

  return T;

  }

  /*============================================

  返回key值最小的结点

  TREE_MINIMUM(x)

  while left[x]!=NIL

  do x <-- left[x]

  return x

  ============================================*/

  struct node* tree_minimum(tree T)

  {

  while(T->left != NULL)

  T=T->left;

  return T;

  }

  /*============================================

  返回key值最大的结点

  TREE_MAXMUM(x)

  while right[x]!=NIL

  do x <-- right[x]

  return x

  ============================================*/

  struct node* tree_maxmum(tree T)

  {

  while(T->right != NULL)

  T=T->right;

  return T;

  }

  /*============================================

     

首页 上一页 1 2 3 4 5 6 7 下一页 尾页 1/15/15
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇c语言连接mysql原代码实例 下一篇C语言随机函数

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: