二叉尋找樹的操作

來源:互聯網
上載者:User

標籤:style   blog   http   color   strong   ar   資料   art   div   

二叉尋找樹按照二叉樹進行組織。二叉尋找樹關鍵字的儲存方式總是瞞住二叉尋找樹性質:

設x為二查尋找樹種一個節點。如果y是x的左子樹中的一個節點,那麼key[x] >= key[y]。如果y是x的右子樹的一個節點,那麼key[x] <= key[y]。

這樣對二叉尋找樹進行中序遍曆就可得到書中所有元素的一個非降序排列。

尋找某一個存在節點的前驅和後繼。某一個節點x的後繼就是大於key[x]的關鍵字中最小的那個節點,前驅就是小於key[x]的關鍵字中最大的那個節點。尋找二叉前驅和後繼節點的演算法如下所示:

 

[cpp] view plaincopyprint?
  1. typedef struct _node {    
  2.     struct _node *left_child;    
  3.     struct _node *right_child;    
  4.     struct _node * parent;  
  5.     ctype    data;    
  6. }node; //樹節點資料結構定義   
  7.   
  8. typedef node* Tree;  
  9.   
  10. //尋找二叉尋找樹中關鍵字最小的節點,返回指向該節點的指標   
  11. Tree tree_minimum(Tree root)  
  12. {  
  13.     Tree p = root;  
  14.     while (p->left_child != null)  
  15.         p = p->left_child;  
  16.     return p;  
  17. }  
  18.   
  19. //尋找二叉尋找樹中關鍵字最大的節點,返回指向該節點的指標   
  20. Tree tree_maxmum(Tree root)  
  21. {  
  22.     Tree p = root;  
  23.   
  24.     while (p->right_child != null)  
  25.     {  
  26.         p = p->right_child;  
  27.     }  
  28.     return p;  
  29. }  
  30.   
  31. //尋找二叉尋找樹中節點x的後繼節點,返回指向該節點的指標   
  32. //在尋找過程中,如果節點x右子樹不為空白,那麼返回右子樹的最小節點即可   
  33. //如果節點x的右子樹為空白,那麼後繼節點為x的某一個祖先節點的父節點,而且該祖先節點是作為其父節點的左兒子   
  34. Tree tree_successor(Tree x)  
  35. {  
  36.     if (x->right_child != null)  
  37.         return tree_minimum(x->right_child);  
  38.       
  39.     //x用來儲存待確定的節點   
  40.     //y為x的父節點   
  41.     Tree y = x->parent;  
  42.   
  43.     while (y != NULL && x == y->right_child)  
  44.     {  
  45.         x = y;  
  46.         y = y->parent;  
  47.     }  
  48.     return y;  
  49. }  
  50.   
  51.   
  52. //尋找二叉尋找樹中節點x的前驅節點,返回指向該節點的指標   
  53. //在尋找過程中,如果節點x左子樹不為空白,那麼返回左子樹的最大節點即可   
  54. //如果節點x的左子樹為空白,那麼前驅節點為x的某一個祖先節點的父節點,而且該祖先節點是作為其父節點的右兒子   
  55. Tree tree_predecessor(Tree x)  
  56. {  
  57.     if (x->left_child != null)  
  58.         return tree_maxmum(x->left_child);  
  59.   
  60.     Tree y = x->parent;  
  61.     while (y != NULL && x == y->left_child)  
  62.     {  
  63.         x = y;  
  64.         y = y->parent;  
  65.     }  
  66.     return y;  
  67. }  

二叉尋找樹的操作

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.