我知道可以編寫遞歸代碼來查找最小高度。但是對於一棵很大的樹(就像左邊的百萬節點和右邊的一個節點一樣) - 這種方法並不好。所以,請讓我知道如果下面的代碼是好的,它使用BFS: -非遞歸程序找到二叉樹的最小高度
if (root == null)
{
return 0;
}
Queue<Node> queue = new Queue<Node>();
queue.Enqueue(root);
int min = 0;
while (queue.Count > 0)
{
Node temp = queue.Dequeue();
if (temp.LeftChild == null)
{
return ++min;
}
if (temp.LeftChild != null)
{
++min;
queue.Enqueue(temp.LeftChild);
}
if (temp.RightChild == null)
{
return ++min;
}
if (temp.RightChild != null)
{
++min;
queue.Enqueue(temp.RightChild);
}
}
return 0;
因此,對於像
1
/\
2 3
/
4
/
6
樹上面返回1,(按照樓(日誌(N)) ?
感謝。
對於百萬節點的情況,遞歸怎麼樣不好呢?你擔心運行時性能,耗盡堆棧還是其他? – razeh 2012-08-12 20:53:04
它性能更好(&耗盡堆棧) - 如果我能快速找到葉節點,爲什麼我必須遍歷整個樹。 (返回1 + Math.Min(GetMin(root.LeftNode),GetMin(root.RightNode)); – parsh 2012-08-12 21:07:05