zoukankan      html  css  js  c++  java
  • c#——树的深度,广度优先遍历与迭代器(IEnumerable<T>)的结合使用

    树是开发工作中比较常见的一种数据结构,园子里有很多文章介绍了对它的遍历,此处我们结合c#的迭代器机制,创建两种树的遍历方法。

    static IEnumerable<T> DepthFirstTravel<T>(T root,Func<T,IEnumerable<T>> getChildren)
            {
    
                if (getChildren == null)
                {
                    throw new ArgumentNullException(nameof(getChildren));
                }
    
                var nodeStack = new Stack<T>();
                nodeStack.Push(root);
                while (nodeStack.Count != 0)
                {
                    var node = nodeStack.Pop();
                    foreach (var child in getChildren(node))
                    {
                        nodeStack.Push(child);
                    }
    
                    yield return node;
                }
            }
            static IEnumerable<T> BreadthFirstTravel<T>(T root, Func<T, IEnumerable<T>> getChildren)
            {
                if (getChildren == null)
                {
                    throw new ArgumentNullException(nameof(getChildren));
                }
    
                var nodeQueue = new Queue<T>();
                nodeQueue.Enqueue(root);
                while (nodeQueue.Count != 0)
                {
                    T node = nodeQueue.Dequeue();
                    foreach (var child in getChildren(node))
                    {
                        nodeQueue.Enqueue(child);
                    }
    
                    yield return node;
                }
            }
  • 相关阅读:
    阿里云服务器购买后的配置指南
    第一阶段总结
    RDD的checkpoint机制和键值对RDD数据分区
    广播变量与累加器
    Spark的监控
    Spark和MR的区别
    hadoop离线项目处理流程
    Flume(一)
    Sparkcore高级应用3
    SparkCore高级应用2(Spark on yarn)
  • 原文地址:https://www.cnblogs.com/ponus/p/11103417.html
Copyright © 2011-2022 走看看