【发布时间】:2012-01-13 10:11:31
【问题描述】:
public void HeightIterative()
{
int counter = 0;
int counter2 = 0;
TreeNode current=root;
if(current != null)
{
while(current.LeftNode!=null)
{
counter++;
current = current.LeftNode;
}
while(current.RightNode!=null)
{
counter2++;
current = current.RightNode;
}
}
int res = 1+Math.Max(counter, counter2);
Console.WriteLine("The Height Of Tree Is: "+res);
}
我写了迭代方法,计算树的高度。但在某些情况下,它无法正常工作。以防万一: 10 1 2 3 4 5 18 17 16 15 14 13 有什么问题。根据此序列树的高度为 6,而我的代码显示为 5。
【问题讨论】:
-
必须是迭代的、BST、BFS....作业?
-
不是作业!如果是,那么我使用作业标签提到它
-
那你为什么坚持使用迭代而不是递归呢?
-
如果你有一个包含 100000 个元素的文本文件并且你想将它存储在二叉树中。然后想知道树的高度。如果您递归执行此操作,则会发生 stackoverflow 异常。这就是原因
-
平衡二叉树中的 100000 个元素是 log(100000)/log(2) ~ 20 次递归调用。没有堆栈溢出异常的可能性。
标签: c# visual-studio-2010 binary-tree binary-search-tree