4.6 设计一个算法,找出二叉查找树中指定结点的“下一个”结点(也即中序后继)。可以假定每个结点都含有指向父节点的连接。

思路:

有两种情况:1)如果该结点存在右子树,则中序后继即为右子树中最小的结点。

      2)如果该结点不存在右子树,则后继结点为使得所给结点在其祖先结点的左子树上的第一个祖先结点,因此一直找父节点,知道找到一个父节点使得该结点在左子树上。

C++实现代码:

#include<iostream>
#include<new>
using namespace std; struct BinarySearchTree
{
int elem;
BinarySearchTree *parent;
BinarySearchTree *left;
BinarySearchTree *right;
BinarySearchTree(int x):elem(x),parent(NULL),left(NULL),right(NULL) {}
}; void insert(BinarySearchTree *&root,int z)
{
BinarySearchTree *y=new BinarySearchTree(z);
if(root==NULL)
{
root=y;
return;
}
else if(root->left==NULL&&z<root->elem)
{
root->left=y;
y->parent=root;
return;
}
else if(root->right==NULL&&z>root->elem)
{
root->right=y;
y->parent=root;
return;
}
if(z<root->elem)
insert(root->left,z);
else
insert(root->right,z);
} void createBST(BinarySearchTree *&root)
{
int arr[]= {,,,,,,,,,};
for(auto a:arr)
insert(root,a);
} void inorder(BinarySearchTree *root)
{
if(root)
{
inorder(root->left);
cout<<root->elem<<" ";
inorder(root->right);
}
} BinarySearchTree* findMin(BinarySearchTree *root)
{
if(root==NULL||!root->left)
return root;
while(root->left)
{
root=root->left;
}
return root;
} BinarySearchTree* findMax(BinarySearchTree *root)
{
if(root==NULL||!root->right)
return root;
while(root->right)
{
root=root->right;
}
return root;
} BinarySearchTree* findProcessor(BinarySearchTree *root,BinarySearchTree* x)
{
if(x->left)
return findMax(x->left);
BinarySearchTree *y=x->parent;
while(y&&y->left==x)
{
x=y;
y=x->parent;
}
return y;
} BinarySearchTree* findSuccessor(BinarySearchTree *x)
{
if(x->right)
return findMin(x->right);
BinarySearchTree *y=x->parent;
while(y&&y->right==x)
{
x=y;
y=x->parent;
}
return y;
} int main()
{
BinarySearchTree *root=NULL;
createBST(root);
inorder(root);
}

最新文章

  1. java实现面向对象和javaScript基于对象的区别&amp;java垃圾回收机制和其他编程语言的比较
  2. 【转】android中ListView的定位:使用setSelectionFromTop实现ListView的position的保持
  3. maven插件
  4. Loadrunner,将http请求返回的中文结果打印出来
  5. ASP.NET MVC SSO单点登录设计与实现(转载)
  6. 统计学 nested_design 嵌套设计
  7. PowerDesigner建表
  8. MYI 文件内容
  9. Win7下Solr4.10.1和TomCat8的安装
  10. Storyboard中使用UIscrollView添加约束的开发总结
  11. Python3.6下scrapy框架的安装
  12. Messenger在MVVM模式中的应用
  13. FloatingActionButton FAB 悬浮按钮
  14. 关于LED效率,这4点你应该知道
  15. [Spring] Aspect Oriented Programming with Spring | AOP | 切面 | 切点
  16. VS插件VisualSVN v5.2.3.0 破解文件
  17. (C/C++学习笔记) 十二. 指针
  18. Git Bash主题配置
  19. java 实现输出姓和名
  20. PHP 字符串补0

热门文章

  1. [Hadoop源码解读](五)MapReduce篇之Writable相关类
  2. Ubuntu Builder —— 一个制作自己的发行版的工具
  3. [Swustoj 24] Max Area
  4. .Net 垃圾回收机制原理(一)
  5. nginx根据域名做http,https分发
  6. 图文教您轻松学会用PS设计制作名片
  7. POJ -- 3842
  8. java命名规范和编程技巧
  9. Clean Code &ndash; Chapter 6 Objects and Data Structures
  10. allegro