国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > C > 正文

C語言 二叉查找樹性質詳解及實例代碼

2020-01-26 14:13:52
字體:
來源:轉載
供稿:網友

二叉查找樹性質

1、二叉樹

每個樹的節點最多有兩個子節點的樹叫做二叉樹。

2、二叉查找樹

一顆二叉查找樹是按照二叉樹的結構來組織的,并且滿足一下性質:

一個節點所有左子樹上的節點不大于蓋節點,所有右子樹的節點不小于該節點。

對查找樹的操作查詢,插入,刪除等操作的時間復雜度和樹的高度成正比, 因此,構建高效的查找樹尤為重要。

查找樹的遍歷

先序遍歷

查找樹的遍歷可以很簡單的采用遞歸的方法來實現。

struct list{  struct list *left;//左子樹  struct list *right;//右子樹  int a;//結點的值};void preorder(struct list *t)//t為根節點的指針{  if(t!=NULL)  {    printf("%d,",t->a);    preorder(t->left);    perorder(t->right);  }}

中序遍歷

struct list{  struct list *left;//左子樹  struct list *right;//右子樹  int a;//結點的值};void preorder(struct list *t)//t為根節點的指針{  if(t!=NULL)  {    preorder(t->left);    printf("%d,",t->a);    perorder(t->right);  }}

后序遍歷

struct list{  struct list *left;//左子樹  struct list *right;//右子樹  int a;//結點的值};void preorder(struct list *t)//t為根節點的指針{  if(t!=NULL)  {    preorder(t->left);    perorder(t->right);    printf("%d,",t->a);  }}

查找樹的搜索

給定關鍵字k,進行搜索,返回結點的指針。

struct list{  struct list *left;//左子樹  struct list *right;//右子樹  int a;//結點的值};struct list * search(struct list *t,int k){  if(t==NULL||t->a==k)    return t;  if(t->a<k)    search(t->right);  else    search(t>left);};

也可以用非遞歸的形式進行查找

struct list{  struct list *left;//左子樹  struct list *right;//右子樹  int a;//結點的值};struct list * search(struct list *t,int k){  while(true)  {    if(t==NULL||t->a==k)    {      return t;      break;    }    if(t->a<k)      t=t->rigth;    else      t=t->left;  }};

最大值和最小值查詢

根據查找樹的性質,最小值在最左邊的結點,最大值的最右邊的 結點,因此,可以直接找到。

下面是最大值的例子:

{  struct list *left;//左子樹  struct list *right;//右子樹  int a;//結點的值};struct lsit *max_tree(struct lsit *t){  while(t!=NULL)  {    t=t->right;  }  return t;};

查找樹的插入和刪除

插入和刪除不能破壞查找樹的性質,因此只需要根據性質,在樹中找到相應的位置就可以進行插入和刪除操作。

struct list{  struct list *left;//左子樹  struct list *right;//右子樹  int a;//結點的值};void insert(struct list *root,struct list * k){  struct list *y,*x;  x=root;  while(x!=NULL)  {    y=x;    if(k->a<x->a)    {      x=x->left;    }    else      x=x->right;  }  if(y==NULL)    root=k;  else if(k->a<y->a)    y->left=k;  else    y->right=k;}

感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表

圖片精選

主站蜘蛛池模板: 灌云县| 衢州市| 昌黎县| 临安市| 高雄市| 墨竹工卡县| 汝州市| 广德县| 彰化市| 泰兴市| 比如县| 蕲春县| 清远市| 平舆县| 罗山县| 长海县| 温宿县| 建德市| 水城县| 宜城市| 张家口市| 河源市| 乌拉特前旗| 荣成市| 喀什市| 扶风县| 禄丰县| 张家川| 嘉峪关市| 德惠市| 民丰县| 上林县| 南部县| 洪泽县| 贵阳市| 张家口市| 霍林郭勒市| 阿克| 隆德县| 宁海县| 页游|