求二叉树中以值为x的结点为根的子树深度

ekisstherain 2009-04-25 07:26:21
编写递归算法:求二叉树中以元素值
为x的结点为根的子树的深度。

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

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

以下是一下具体的例子:
如图:



此树为:T = F(D,H(#,J(#,T))) (说明:‘#’表示结点为空)
函数输出:Depth(T, 'H') = 3

希望有高手可以帮下我啦~~~~~
在线等……………………
...全文
1987 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
吕津 2009-05-06
  • 打赏
  • 举报
回复
speeder53 2009-04-27
  • 打赏
  • 举报
回复
mk
ekisstherain 2009-04-26
  • 打赏
  • 举报
回复
自己写的,帮忙想个问题解决的办法~~~~谢谢
初雪 11:05:10
int GetDepth(BiTree bt)
{
int m,n;
if(bt)
{
m=GetDepth(bt->lchild);
n=GetDepth(bt->rchild);
return (m>=n?m+1:n+1);
}
else
return 0;
}


int Depthx(BiTree T, TElemType x)
/* 求二叉树中以值为x的结点为根的子树深度 */
{
if(T->data==x)
{
return GetDepth(T);
exit (1);
}
else
{
if(T->lchild)
return Depthx(T->lchild,x);
if(T->rchild)
return Depthx(T->rchild,x);
}
}
初雪 11:07:12
问题:
为什么这里:
if(T->lchild)
return Depthx(T->lchild,x);
if(T->rchild)
return Depthx(T->rchild,x);
执行时,当T->lchild和T->rchild都为空时,为什么不能返回上一个结点,而是输出0后退出了
ekisstherain 2009-04-26
  • 打赏
  • 举报
回复
算了~~还是靠自己吧

给出最后结果啦

int GetDepth(BiTree bt)//求树的深度子函数
{
int m,n; //记录返回的个数
if(bt) //非空执行
{
m=GetDepth(bt->lchild); //对左子树递归
n=GetDepth(bt->rchild); //对右子树递归
return (m>=n?m+1:n+1); //返回最深的度数
}
else //bt空,返回0
return 0;
}

int Depthx(BiTree T, TElemType x)
/* 求二叉树中以值为x的结点为根的子树深度 */
{
int m,n;
if(!T) //空,返回0
return 0;
if(T->data==x) //找到T,求T的深度
return GetDepth(T); //返回T的深夜
else
{
if(T->lchild) //向左子树找T
m=Depthx(T->lchild,x);
if(T->rchild) //向右子树找T
n=Depthx(T->rchild,x);
}
return (m>=n?m:n); //返回向下递归的最大深度
}
nickyjay0501 2009-04-25
  • 打赏
  • 举报
回复
帮顶
liliangbao 2009-04-25
  • 打赏
  • 举报
回复
帮顶
ekisstherain 2009-04-25
  • 打赏
  • 举报
回复
下面是我自己写的一个算法,不过还是存在问题,看有没有可以给点意见的:

int Depthx(BiTree T, TElemType x)
/* 求二叉树中以值为x的结点为根的子树深度 */
{
int m,n;
if(T)
{
if(m==0)
{
if(T->data==x)
m=1;
if(T->data!=x)
{
if(T->lchild)
return m=Depthx(T->lchild,x);
if(T->rchild)
return m=Depthx(T->rchild,x);
}
}
if(m!=0)
{
if(!T) return 0;
if(T->lchild)
m=Depthx(T->lchild,x)+1;
if(T->rchild)
n=Depthx(T->rchild,x)+1;
return (m>n?m:n)-1;
}
}
}
baihacker 2009-04-25
  • 打赏
  • 举报
回复



BiTree find(BiTree root, Type value)
{
if (root == NULL) return NULL;
if (root->value == value) return root;
BiTree ans = find(root->left, value);
if (ans) return ans;
return find(root->right, value);
}

int depth(BiTree root)
{
if (root == NULL) return 0;
int l = depth(root->left);
int r = depth(root->right);
return max(l, r)+1;
}

depth(find(root, value));
为所求

64,648

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧