用递归写个求二叉树的深度的函数

sms88 2003-04-17 07:27:21
用递归写个求二叉树的深度的函数,而且写出其执行的每一步过程
...全文
278 11 打赏 收藏 转发到动态 举报
写回复
用AI写文章
11 条回复
切换为时间正序
请发表友善的回复…
发表回复
suguanqun 2003-04-21
  • 打赏
  • 举报
回复
up
Spectrum 2003-04-21
  • 打赏
  • 举报
回复
up
lfengchao 2003-04-21
  • 打赏
  • 举报
回复
#include "stdio.h"
#include "alloc.h"
typedef char Elemtype;

typedef struct Bitnode
{Elemtype data;
struct Bitnode *lchild,*rchild;
}Bitnode,*Bittree;

Bittree creatbittree()
{ Bittree bt;
char ch;
scanf("%c",&ch);
if (ch==' ') bt=NULL;
else{
bt=(Bittree)malloc(sizeof(Bitnode));
bt->data=ch;
bt->lchild=creatbittree();
bt->rchild=creatbittree();
}
return bt;
}

int Bhigh(Bittree bt)
{
int H,HL,HR;
if(bt==NULL) H=0;
else
{
HL=Bhigh(bt->lchild);
HR=Bhigh(bt->rchild);
H=max(HL,HR)+1;
}
return H;
}

int max(int x,int y)
{
if(x>y)
return x;
else
return y;
}

main()
{
Bittree Tree;
int H;
Tree=creatbittree();
H=Bhigh(Tree);
printf("\nThe high of the tree is:%d\n",H);
}
MelodyCanFLY 2003-04-21
  • 打赏
  • 举报
回复
关注
sms88 2003-04-21
  • 打赏
  • 举报
回复
不是我偷懒呀,而是拿一个二叉数代入那个递归函数,我就不知道怎么计算到结果
huangstar1108 2003-04-21
  • 打赏
  • 举报
回复
很多书上都有,不要偷懒呀!
bjack 2003-04-18
  • 打赏
  • 举报
回复
template<class T>
int BinaryTree<T>::Height(BinaryTreeNode<T>*t) const
{
if(!t) return 0;
int hl = Height(t->LeftChild);
int hr = Height(t->RightChild);
if (hl > hr) return ++hl;
else return ++hr;
}
shishiXP 2003-04-17
  • 打赏
  • 举报
回复
struct BTNode
{
BTNode *lchild;
BTNode *rchild;
BTNode()
{
lchild=0;
rchild=0;
}
};

int getdepth( BTNode* BT )
{
int ldepth = 0;
int rdepth = 0;

if( BT == NULL )return 0;
ldepth=getdepth( BT->lchild );
rdepth=getdepth( BT->rchild );
return 1 + ( ldepth > rdepth ? ldepth : rdepth );
}

加分!!!!!!!!!!!!!!!!!
alexGIS 2003-04-17
  • 打赏
  • 举报
回复
不太明白你的要求。
什么叫写出其执行的每一步?
像计算机一样去读读源代码不就明白了程序到底怎么走的吗?
sms88 2003-04-17
  • 打赏
  • 举报
回复
可以用一个随便的二叉树写出其执行的每一步吗?
alexGIS 2003-04-17
  • 打赏
  • 举报
回复
int GetDepth( BTNode* BT )
{
int depth = 0;
int temp1 = 0;
int temp2 = 0;

if( BT == NULL )
{
return 0;
}
else
{
temp1 = GetDepth( BT->lChild );
temp2 = GetDepth( BT->rChild );

depth = temp1 > temp2 ? temp1 : temp2;
depth++;

return depth;
}
}

69,371

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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