当前位置:   article > 正文

7. 二叉排序树的搜索、插入、删除,时间复杂度

7. 二叉排序树的搜索、插入、删除,时间复杂度

二叉排序树又称二叉查找树,它或是一棵空的二叉树,或是具有下列性质的二叉树:

  • 若它的左子树不空,则左子树上所有节点的值均小于根节点的值
  • 若它的右子树不空,则右子树上所有节点的值均大于根节点的值
  • 它的左右子树也都是二叉排序树
由上述定义可知, 中虚遍历二叉排序树可以得到一个按关键码有序的序列。

  1. template<class T>
  2. struct BiNode
  3. {
  4. T data;
  5. BiNode<T>*lchild,rchild;
  6. }
  7. class BiSortTree
  8. {
  9. public:
  10. BiSortTree(int a[],int n);
  11. ~BiSortTree();
  12. void InsertBST(BiNode<int>*root,BiNode<int>*s);
  13. void DeleteBST(BiNode<int>*p,BiNode<int>*f);
  14. BiNode<int>*SearchBST(BiNode<int>*root,int k);
  15. private:
  16. BiNode<int>*root;
  17. }
  18. void BiSortTree::InsertBST(BiNode<int>*root,BiNode<int>*s)
  19. {
  20. if(root==NULL)
  21. root=s;
  22. else if(s->data<root->data)
  23. InsertBST(root->lchild,s);
  24. else
  25. InsertBST(root->rchild,s);
  26. }
  27. BiSortTree::BiSortTree(int r[],int n)
  28. {
  29. for(int i=0;i<n;i++)
  30. {
  31. BiNode<int>s=new BiNode<int>;
  32. s->data=r[i];
  33. s->lchild=s->rchild=NULL;
  34. InsertBST(root,s);
  35. }
  36. }
  37. //在二叉排序树中删除一个节点f的左孩子节点p的算法:
  38. //1.若节点p是叶子,则直接删除节点p
  39. //2.若节点p只有左子树,则需重接p的左子树;若节点p只有右子树,则需重接p的右子树
  40. //3.若节点p的左右子树都不为空,则
  41. // 3.1查找节点p的右子树上的最左下节点s以及节点s的双亲节点par
  42. // 3.2将节点s的数据域替换到被删除节点p的数据域
  43. // 3.3若节点p的右孩子无左子树,则将s的右子树接到par的右子树上;否则将s的右子树接到节点par的左子树上
  44. // 3.4删除节点s;
  45. void BiSortTree::DeleteBST(BiNode<int>*p,BiNode<int>*f)
  46. {
  47. if((p->lchild==NULL)&&(p->rchild)==NULL)
  48. {
  49. f->lchild=NULL;
  50. delete p;
  51. }
  52. else if(p->rchild==NULL)
  53. {
  54. f->lchild=p->lchild;
  55. delete p;
  56. }
  57. else if(p->lchild==NULL)
  58. {
  59. f->lchild=p->rchild;
  60. delete p;
  61. }
  62. else{
  63. BiNode<int>*par=p;
  64. BiNode<int>*s=p->rchild;
  65. while(s->lchild!=NULL)
  66. {
  67. par=s;
  68. s=s->lchild
  69. }
  70. p->data=s->data;
  71. if(par==p)
  72. par->rchild=s->rchild;
  73. else
  74. par->lchild=s->rchild;
  75. delete s;
  76. }
  77. }
  78. BiNode<int>*BiSortTree::SearchBST(BiNode<int>*root,int k)
  79. {
  80. if(root==NULL)
  81. return NULL;
  82. else if(root->data==k)
  83. return root;
  84. else if(root->date>k)
  85. return SearchBST(root->lchild,k);
  86. else if(root->data<k)
  87. return SearchBST(root->rchild,k);
  88. }

给定值的比较次数等于给定值节点在二叉排序树中的层数。如果二叉排序树是平衡的,则n个节点的二叉排序树的高度为Log 2n+1,其查找效率为O(Log 2n),近似于折半查找。如果二叉排序树完全不平衡,则其深度可达到n,查找效率为O(n),退化为顺序查找。一般的,二叉排序树的查找性能在O(Log 2n)到O(n)之间。因此,为了获得较好的查找性能,就要构造一棵平衡的二叉排序树。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/人工智能uu/article/detail/844546?site
推荐阅读
相关标签
  

闽ICP备14008679号