c# - 广度优先遍历

标签 c# .net algorithm data-structures

我试图解决一个面试问题,但为此我必须逐级遍历二叉树。我设计了具有以下变量的 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;
    }

最佳答案

广度优先搜索通常使用队列实现,深度优先搜索使用堆栈

Queue<Node> q = new Queue<Node>();
q.Enqueue(root);
while(q.Count > 0)
{
    Node current = q.Dequeue();
    if(current == null)
        continue;
    q.Enqueue(current.Left);
    q.Enqueue(current.Right);

    DoSomething(current);
}

作为在出队后检查 null 的替代方法,您可以在添加到队列之前进行检查。我没有编译代码,所以它可能包含一些小错误。


与 LINQ 良好集成的更高级(但更慢)的版本:

public static IEnumerable<T> BreadthFirstTopDownTraversal<T>(T root, Func<T, IEnumerable<T>> children)
{
    var q = new Queue<T>();
    q.Enqueue(root);
    while (q.Count > 0)
    {
        T current = q.Dequeue();
        yield return current;
        foreach (var child in children(current))
            q.Enqueue(child);
    }
}

它可以与 Node 上的 Children 属性一起使用:

IEnumerable<Node> Children { get { return new []{ Left, Right }.Where(x => x != null); } }

...

foreach(var node in BreadthFirstTopDownTraversal(root, node => node.Children))
{
   ...
}

关于c# - 广度优先遍历,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5111645/

相关文章:

c# - 在 ViewModel 中为命令使用私有(private)集的目的是什么?

c# - C#如何获取当年的第一天和最后一天

c# - 将结构数组从 .NET 编码到 C++ : when does it do copying?

java - 从Java数组中获取前四名最大值

c# - Mapnik.NET 图层数据源路径

c# - C#中的函数Socket.Select()在linux操作系统中使用epoll吗?

.net - 将 RouteValueDictionary 转换为匿名对象的快速方法?

c# - 一路async await async

c# - 查找对象的唯一排列

algorithm - 两个区间的最大和