|
被迫用void函数递归遍历二叉树,不知道找到所求的结点后怎么结束递归,我停不下来,大家help
问题如下
编写递归算法,求二叉排序树上的小于x且
最靠近x的值a和大于x且最靠近x的值b。如果这样的
a或b值不存在,则分别返回MINV和MAXV。
实现下列函数:
void OutX(BiTree t, KeyType x, KeyType &a, KeyType &b);
/* a: Return the nearest and smaller value to x, */
/* but return MINV if no the value in t. */
/* b: Return the nearest and larger value to x. */
/* but return MAXV if no the value in t. */
二叉树的类型BiTree定义如下:
typedef struct {
KeyType key;
... ... // 其他数据域
} ElemType;
typedef struct BiTNode {
ElemType data;
BiTNode *lchild,*rchild;
}BiTNode, *BiTree;
个人思路:
1。中序遍历二叉树,定义静态变量pre,记录前驱结点的数据域关键字
2。系统编译一次以后多次调用这个函数来测试,所以每次递归完成以后必须把pre赋成初值,供下一次调用的时候用
……思路很乱,不知道怎么讲,直接贴代码吧 ,委屈大家读一下我恶心的代码-
- void OutX(BiTree t, KeyType x, KeyType &a, KeyType &b)
- /* a: Return the nearest and smaller value to x, */
- /* but return MINV if no the value in t. */
- /* b: Return the nearest and larger value to x. */
- /* but return MAXV if no the value in t. */
- {
- static KeyType pre=255;
- static int tag=0;
- if(t->rchild) tag++; //tag是标志位,右子树非空加1,访问右子树时减1,最后右子树为空且tag为零时表示遍历完成没找到比x大的值,此时b赋MAXV
- if (t->lchild) OutX(t->lchild,x,a,b); //中序遍历
- if(b已赋值) return;
- if(pre==255 && t->data.key>=x) a=MINV; /*pre的初始值为255,本来是要以pre是否为255来判断t是不是最左下的结点,但是在b赋值以后同样会把pre置为255,所以如果b已赋值的话,必须在上一行就结束程序,问题就在于上一行怎样判断b是否已赋值*/
- if(pre<x && t->data.key>=x) //给a赋值
- a=pre;
- if(pre<=x && t->data.key>x){ //给b赋值,以及把静态变量“初始化”,供下次调用函数时使用
- b=t->data.key;
- pre=255;
- tag=0;
- return;
- }
- pre=t->data.key; //pre赋值
- if(t->rchild){ //访问右子树
- tag--;
- OutX(t->rchild,x,a,b);
- }
- if(pre==255 || b==MAXV) return; //b已赋过值,退出函数
- if(tag==0){ //b没有赋过值,且遍历已经完成,把b置MAXV,且把最后一个结点的数据域的关键字赋给a
- b=MAXV;
- a=t->data.key;
- pre=255;
- tag=0;
- }
- }
复制代码 主要问题在红色部分,如何区分b赋值后的状态和访问最左下结点时的状态
代码中不能上色 ,主要问题是一下几句- if (t->lchild) OutX(t->lchild,x,a,b); //中序遍历
- if(b已赋值) return;
- if(pre==255 && t->data.key>=x) a=MINV; /*pre的初始值为255,本来是要以pre是否为255来判断t是不是最左下的结点,但是在b赋值以后同样会把pre置为255,所以如果b已赋值的话,必须在上一行就结束程序,问题就在于上一行怎样判断b是否已赋值*/
复制代码 思路很乱,注释也很乱,希望大家将就着点看一下[em06]
弄了好多天都没能把这个弄完,希望大家帮帮忙
[ 本帖最后由 874 于 2008-6-9 03:57 编辑 ] |
|