计算二叉树高度的题目,求助

sdnd2000 2008-04-16 03:53:00
Consider the task of computing the height of a binary tree. ( We define the height of a leaf node to be 0), Suppose each node contains ponters LCHILD(left child) and RCHILD(right child).

a.write a pseudo code
c. Analyze the time complexity of the algorithm in terms of the number of nodes n and the height of the tree h.

我是这样写的
int height( pter r)
{ if r=NULL) return -1
if (height (r->LCHILD)>height(r->RCHILD))
return( 1+height(r->LCHILD))
else return (1+height(r->RCHILD));
}

感觉不是很高效啊,希望高人指点
...全文
399 6 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
sdnd2000 2008-04-17
  • 打赏
  • 举报
回复
谢谢,那用n和h表示复杂度该怎么表示呀
sdnd2000 2008-04-17
  • 打赏
  • 举报
回复
谢谢,那用n和h表示复杂度该怎么表示呀
rushman 2008-04-16
  • 打赏
  • 举报
回复
啊!重复了 -_-!
rushman 2008-04-16
  • 打赏
  • 举报
回复
除了没必要多次计算左右子树的高度外,其他没什么要改的
#define MAX(x,y) (x>y?x:y)

int height(pter r){
int lh,rh;
if(r == NULL)return -1;
lh = height(r->LCHILD);
rh = height(r->RCHILD);
return (1 + MAX(lh,rh));
}
sdnd2000 2008-04-16
  • 打赏
  • 举报
回复
非常感谢!
tailzhou 2008-04-16
  • 打赏
  • 举报
回复
晕,return还调一次;

int height(pter r)
{
int i,j;
if (r==NULL) return -1;
i=height(r->LCHILD);
j=height(r->RCHILD);
return i>j?i+1:j+1;
}

复杂度o(n);

33,027

社区成员

发帖
与我相关
我的任务
社区描述
数据结构与算法相关内容讨论专区
社区管理员
  • 数据结构与算法社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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