【发布时间】:2018-01-23 21:51:46
【问题描述】:
我试图解决一个面试问题,但为此我必须逐级遍历二叉树。我设计了具有以下变量的 BinaryNode
private object data;
private BinaryNode left;
private BinaryNode right;
有人可以帮忙在我的 BinarySearchTree 类中编写 BreadthFirstSearch 方法吗?
更新:感谢大家的投入。所以这是面试问题。 “给定一个二叉搜索树,设计一个算法,在每个深度创建一个所有节点的链表(即,如果你有一个深度为 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;
}
【问题讨论】:
-
到目前为止你尝试过什么?你能用简单的英语解释一下算法应该做什么(即给出伪代码)吗?
-
维基百科尽职调查怎么样? en.wikipedia.org/wiki/Breadth-first_search
标签: c# .net algorithm data-structures