④ 编写递归算法:求二叉树中以元素值
为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);
}