我试图解决一道面试题,但需要逐层遍历二叉树。我已经设计了带有以下变量的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;
}