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;
            }
        }

 

转载于:https://www.cnblogs.com/ponus/p/11103417.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值