数据结构复习(求特定子树的高度)

来源:互联网 发布:dw软件怎么用 编辑:程序博客网 时间:2024/05/23 10:45

④  编写递归算法:求二叉树中以元素值
为x的结点为根的子树的深度。

要求实现下列函数:
int Depthx(BiTree T, TElemType x);
/* 求二叉树中以值为x的结点为根的子树深度 */

二叉链表类型定义:
typedef struct BiTNode {
    TElemType data;
    BiTNode  *lchild, *rchild;
} BiTNode, *BiTree;

BiTree search(BiTree t,TElemType x)
{
  BiTree p;
  if(!t||t->data==x)
    return t;
  if(p=search(t->lchild,x))
    return p;
  else
    return search(t->rchild,x);
}

int count(BiTree t)
{   
 if(!t)
    return 0;
 else
    return 1+(count(t->lchild)>count(t->rchild)?
        count(t->lchild):count(t->rchild));
}

int Depthx(BiTree T, TElemType x)
/* 求二叉树中以值为x的结点为根的子树深度 */
{
 BiTree pb=search(T,x);
 return count(pb);
}

 

原创粉丝点击