歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> 構造一個二叉查找樹-C++實現

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

日期:2017/3/1 10:08:33   编辑:Linux編程

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

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