求二叉树的深度

勿腻阳 2009-09-20 03:52:01
有一个二叉树,用C#语言设计一个算法,求出他的深度。
...全文
284 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
thishaha 2009-09-21
  • 打赏
  • 举报
回复
树的深度最好作为节点的一个分量
wuyi8808 2009-09-21
  • 打赏
  • 举报
回复
查了一下,树的高度和深度的定义是不一样的,因此更正一下:
/*
二叉树的深度定义为二叉树中层数最大的叶结点的层数。
二叉树的高度定义为二叉树中层数最大的叶结点的层数加1。
*/
using System;

class Tree
{
public Tree LChild = null; // 左子树
public Tree RChild = null; // 右子树

// 树的深度
public static int Depth(Tree t)
{
if (t == null) return -1;
return Math.Max(Tree.Depth(t.LChild), Tree.Depth(t.RChild)) + 1;
}

// 树的高度
public static int Height(Tree t)
{
return Tree.Depth(t) + 1;
}
}

class Program
{
static void Main()
{
Tree child = new Tree();
child.LChild = new Tree();
Console.WriteLine(Tree.Depth(child));

Tree tree = new Tree();
tree.RChild = child;
Console.WriteLine(Tree.Depth(tree));
}
}
wuyi8808 2009-09-20
  • 打赏
  • 举报
回复
using System;

class Tree
{
public Tree LChild = null; // 左子树
public Tree RChild = null; // 右子树

// 树的深度
public static int Depth(Tree t)
{
if (t == null) return 0;
return Math.Max(Tree.Depth(t.LChild), Tree.Depth(t.RChild)) + 1;
}
}

class Program
{
static void Main()
{
Tree child = new Tree();
child.LChild = new Tree();
Console.WriteLine(Tree.Depth(child));

Tree tree = new Tree();
tree.RChild = child;
Console.WriteLine(Tree.Depth(tree));
}
}
光宇广贞 2009-09-20
  • 打赏
  • 举报
回复
树过大过深的话………递归会栈溢出,使用 F# 可以避免这一问题。

http://blog.csdn.net/hikaliv/archive/2009/09/13/4548561.aspx
acdbxzyw 2009-09-20
  • 打赏
  • 举报
回复
[Quote=引用 4 楼 kx_z2007 的回复:]
C#不是很了解...
[/Quote]
勿腻阳 2009-09-20
  • 打赏
  • 举报
回复
能用C#写一个吗?C++不是很了解,谢谢了!
love_autumn 2009-09-20
  • 打赏
  • 举报
回复
不懂c#额~~~
勿腻阳 2009-09-20
  • 打赏
  • 举报
回复
顶一下
acdbxzyw 2009-09-20
  • 打赏
  • 举报
回复
int depth(Tree T)
{
if(T == NULL) return 0;
return
depth(T->lchild)>depth(T-rchild) ? 1+depth(T->lchild) : 1+depth(T->rchild);
}

33,028

社区成员

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

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