这样求二叉树的深度是否合理?

csdn5211 2006-12-21 09:17:30
用先序非递归遍历,设置一个变量,每次进栈时加一,出栈时减一,如果当前访问节点是叶子节点,就把这个变量记录下来。最后求所有记录下来的最大值。
...全文
294 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
cjq87 2006-12-21
  • 打赏
  • 举报
回复
//栈的函数写的不是很好
//退栈的时候隐含了depth--
#include <stdio.h>
#include <malloc.h>
#define M 10 /* 假设二叉树最多的层数 */
typedef struct BiTNode
{
char data;
struct BiTNode *lchild,*rchild;
}BiTNode,*BiTree;
typedef struct Stack
{
char data;
BiTree * top;
BiTree * base;
}Stack;
void InitStack(Stack &S)
{
S.base=(BiTree *)malloc(sizeof(BiTree)*M);
S.top=S.base;
}
void push(Stack &S,BiTree p)
{
*S.top=p;
S.top++;
}
void pop(Stack &S,BiTree &p)
{
S.top--;
p=*S.top;
}
int StackEmpty(Stack S)
{
if(S.base==S.top)
return 1;
else
return 0;
}
void CreateBiTree(BiTree &T) /* 按先序序列建立一个二叉树 */
{
char c;
scanf("%c",&c);
if (c=='#')
T=NULL;
else
{
if (T)
{
T = (BiTNode *)malloc(sizeof(BiTNode));
T->data = c; /* 生成根结点 */
CreateBiTree(T->lchild); /* 构造左子树 */
CreateBiTree(T->rchild); /* 构造右子树 */
}
}
}

int DepthTree(BiTree &T)
{
BiTree p;
int depth, max;
Stack S;
InitStack(S);
p=T;
depth=max=0;
while(p||!StackEmpty(S))
{
if(p)
{
push(S,p);
p=p->lchild;
depth++;
if(max<depth)
max=depth;
}
else
{
pop(S,p);
p=p->rchild;
}
}
return max;
}
void main()
{
BiTree T;
printf("Please input(end with \"#\"):\n");
CreateBiTree(T);
printf("The depth of the tree is:");
printf("%d\n",DepthTree(T));
}
cjq87 2006-12-21
  • 打赏
  • 举报
回复
是合理的
我以前用这种方法编过这个程序

33,008

社区成员

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

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