我试图解决一个面试问题,但为此我必须逐级访问二叉树。我已经设计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