Advertisement
Guest User

Untitled

a guest
Mar 29th, 2017
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.52 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4.  
  5. namespace Delegates.TreeTraversal
  6. {
  7.     public static class Traversal
  8.     {
  9.         private static IEnumerable<TResult> Travers<TData,TResult>(
  10.             TData data,
  11.             Func<TData, IEnumerable<TResult>> getResults,
  12.             Func<TData, IEnumerable<TData>> updateStack)
  13.         {
  14.             var stack = new Stack<TData>();
  15.             stack.Push(data);
  16.             while (stack.Count > 0)
  17.             {
  18.                 var temp = stack.Pop();
  19.                 foreach (var res in getResults(temp))
  20.                     yield return res;
  21.                 foreach (var res in updateStack(temp))
  22.                     stack.Push(res);
  23.             }
  24.         }
  25.         public static IEnumerable<TParameters> GetBinaryTreeValues<TParameters>(BinaryTree<TParameters> data)
  26.         {
  27.             return Travers(
  28.                 data,
  29.                 x => new List<TParameters> {x.Value},
  30.                 tree => new[] {tree.Left, tree.Right}.Where(x => x != null));
  31.         }
  32.         public static IEnumerable<Job> GetEndJobs(Job data)
  33.         {
  34.             return Travers(
  35.                 data,
  36.                 x => x.Subjobs.Count == 0 ? new[] {x} : new Job[0],
  37.                 tree => tree.Subjobs);
  38.         }
  39.         public static IEnumerable<Product> GetProducts(ProductCategory data)
  40.         {
  41.             return Travers(
  42.                 data,
  43.                 x => x.Products,
  44.                 tree => tree.Categories);
  45.         }
  46.     }
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement