歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux編程 >> Linux編程

構造一個二叉查找樹-C++實現

根據輸入的數組元素,構造一個二叉查找樹。

  1. #include <iostream>  
  2. using namespace std; 
  3. /*二叉查找樹結構*/ 
  4. typedef struct BSTree 
  5. { 
  6.     int node_value; 
  7.     struct BSTree * left; 
  8.     struct BSTree * right; 
  9. }Tree; 
  10. /*****構造二叉查找樹**********************************************/ 
  11. void  CreateBSTree(Tree * root,int node_value); 
  12. Tree * CreateBSTree(int * array_list,int array_length); 
  13.  
  14. void Print(Tree* root); 
  15.  
  16. /***************************************************************/ 
  17.  
  18. /***************************************************************/ 
  19. int main(int argc,char * argv) 
  20. { 
  21.     Tree * root = NULL; 
  22.     int list[]={5,3,4,9,1,7,11}; 
  23.     root = CreateBSTree(list,7); 
  24.     std::cout<<"Cearte BSTree."<<std::endl; 
  25.     Print(root); 
  26.     return 0; 
  27. } 
  28.  
  29. /*生成二叉查找樹*/ 
  30. Tree * CreateBSTree(int * array_list,int array_length) 
  31. { 
  32.     if(array_length <= 0) 
  33.     { 
  34.         return false; 
  35.     } 
  36.     Tree * root = NULL; 
  37.     root = new BSTree(); 
  38.     root->left = NULL; 
  39.     root->right = NULL; 
  40.     root->node_value = array_list[0]; 
  41.     for(int i=1;i<array_length;i++) 
  42.     { 
  43.         CreateBSTree(root,array_list[i]); 
  44.     } 
  45.     return root; 
  46. } 
  47. void  CreateBSTree(Tree * root,int node_value) 
  48. { 
  49.     if(root == NULL) 
  50.     { 
  51.         return ; 
  52.     } 
  53.     if(root->node_value > node_value) 
  54.     { 
  55.         if(root->left == NULL) 
  56.         { 
  57.             Tree * node = new Tree(); 
  58.             node->left = NULL; 
  59.             node->right = NULL; 
  60.             node->node_value = node_value; 
  61.             root->left = node; 
  62.         } 
  63.         else 
  64.         { 
  65.              CreateBSTree(root->left,node_value); 
  66.         } 
  67.     } 
  68.     else 
  69.     { 
  70.         if(root->right == NULL) 
  71.         { 
  72.             Tree * node = new Tree(); 
  73.             node->left = NULL; 
  74.             node->right = NULL; 
  75.             node->node_value = node_value; 
  76.             root->right = node; 
  77.         } 
  78.         else 
  79.         { 
  80.              CreateBSTree(root->right,node_value); 
  81.         } 
  82.     } 
  83. } 
  84. /*中序排序輸出二叉查找樹*/ 
  85. void Print(Tree* root) 
  86. { 
  87.     if(root == NULL) 
  88.     { 
  89.         return ; 
  90.     } 
  91.     Print(root->left); 
  92.     std::cout<<root->node_value<<"\t"; 
  93.     Print(root->right); 
  94. } 
Copyright © Linux教程網 All Rights Reserved