1,设二叉树以二叉链表形式存放,用类C语言设计非递归算法判断一棵根结点为T的二叉树是否为
二叉排序树
。
(思路:从根结点开始访问,每次从栈中取出一个节点,将其子结点加入到栈中)
这里先给出递归的解法:
int IsSearchTree(const BTNode *t){ if(!t) //空二叉树情况 return 1; else if(!(t->lchild) && !(t->rchild))//左右子树都无情况 return 1; else if((t->lchild) && !(t->rchild)){//只有左子树情况 if(t->lchild->data>t->data) return 0; else return IsSearchTree(t->lchild); } else if((t->rchild) && !(t->lchild)){//只有右子树情况 if(t->rchild->data<t->data) return 0; else return IsSearchTree(t->rchild); } else{ //左右子树全有情况 if((t->lchild->data>t->data) ||(t->rchild->data<t->data)) return 0; else return IsSearchTree(t->lchild) && IsSearchTree(t->rchild); } }
2,设二叉排序树以二叉链表形式存放,用类C语言设计递归算法求一棵根结点为T的二叉树上小于k且最靠近k的数据元素a和大于k且最靠近k的数据元素b。
实现下列函数: 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;
代码如下:
void Out(BiTree t, KeyType x, KeyType &a, KeyType &b) { if( t ) if( x == t->data.key ) {Out( t -> lchild, x, a, b ); Out( t -> rchild, x, a, b );} else if( x < t->data.key ) {b = t -> data.key;Out( t -> lchild, x, a, b );} else {a = t -> data.key; Out( t -> rchild, x, a, b );} } 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. */ { a = '<'; b = '>'; Out( t, x, a, b ); }