6.44编写递归算法:求二叉树中以元素值为x的结点为根的子树的深度,要求实现下列函数
int Depthx(BiTree T, TElemType x);
/*求二叉树中以值为x的结点为根的子树深度*/
typedef struct BiTNode {
TElemType data;
BiTNode *lchild, *rchild;
} BiTNode, *BiTree;
BiTree pre(BiTree T,TElemType x)
{
if(T)
{
BiTree tempT;
if(T->data==x)return T;
if(!(tempT=pre(T->lchild,x)))
return pre(T->rchild,x);
return tempT;
}
return NULL;
}
int Depth(BiTree T)
{
int ldepth,rdepth;
if(!T)return 0;
ldepth=Depth(T->lchild);
rdepth=Depth(T->rchild);
if(ldepth>rdepth)return ldepth+1;
return rdepth+1;
}
int Depthx(BiTree T, TElemType x)
{
BiTree btx=pre(T,x);
return Depth(btx);
}