我試圖解決一個面試問題,但爲此我必須逐級訪問二叉樹。我已經設計BinaryNode用具有下述可變廣度優先遍歷
private object data;
private BinaryNode left;
private BinaryNode right;
可能有人請幫忙給我寫BinarySearchTree類裏面的廣度優先搜索方法?
更新:謝謝大家的投入。所以這是面試問題。 「給定一個二叉搜索樹,設計一個算法,該算法創建每個深度的所有節點的鏈表(即,如果您有一棵深度爲D的樹,則將有D個鏈表)」。
這是我的方法,讓我知道你的專家評論。
public List<LinkedList<BNode>> FindLevelLinkList(BNode root)
{
Queue<BNode> q = new Queue<BNode>();
// List of all nodes starting from root.
List<BNode> list = new List<BNode>();
q.Enqueue(root);
while (q.Count > 0)
{
BNode current = q.Dequeue();
if (current == null)
continue;
q.Enqueue(current.Left);
q.Enqueue(current.Right);
list.Add(current);
}
// Add tree nodes of same depth into individual LinkedList. Then add all LinkedList into a List
LinkedList<BNode> LL = new LinkedList<BNode>();
List<LinkedList<BNode>> result = new List<LinkedList<BNode>>();
LL.AddLast(root);
int currentDepth = 0;
foreach (BNode node in list)
{
if (node != root)
{
if (node.Depth == currentDepth)
{
LL.AddLast(node);
}
else
{
result.Add(LL);
LL = new LinkedList<BNode>();
LL.AddLast(node);
currentDepth++;
}
}
}
// Add the last linkedlist
result.Add(LL);
return result;
}
你嘗試過這麼遠嗎?你能用簡單的英語來解釋算法應該做什麼(即給出僞代碼)嗎? – Davidann 2011-02-24 23:08:06
維基百科的回合盡職調查? http://en.wikipedia.org/wiki/Breadth-first_search – 2011-02-24 23:08:57