数据结构二叉树的两个题目

22 篇文章 0 订阅
18 篇文章 1 订阅
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 ); 
}

  • 1
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值