C#构建树形结构数据(全部构建,查找构建)

2019-12-30 18:13:39刘景俊

递归遍历至此结束。

3、非递归遍历

非递归遍历在操作中不需要递归方法的参与即可实现Tree的拼接

对于以上的代码,我们不需要修改,只需要定义一个非递归遍历方法NotRecursion:


    public static void NotRecursion()
    {
      #region 非递归遍历

      System.Diagnostics.Stopwatch sw2 = new System.Diagnostics.Stopwatch();

      sw2.Start();
      Dictionary<string, TreeObejct> dtoMap = new Dictionary<string, TreeObejct>();
      foreach (var item in models)
      {
        dtoMap.Add(item.id, item);
      }
      IList<TreeObejct> result = new List<TreeObejct>();
      foreach (var item in dtoMap.Values)
      {
        if (item.pId == "0")
        {
          result.Add(item);
        }
        else
        {
          if (dtoMap.ContainsKey(item.pId))
          {
            dtoMap[item.pId].AddChilrden(item);
          }
        }


      }

      sw2.Stop();
      Console.WriteLine("----------非递归遍历用时:" + sw2.ElapsedMilliseconds + "----------线程名称:" + t2.Name + ",线程ID:" + t2.ManagedThreadId);

      #endregion
    }

编写main函数:


    private static IList<TreeObejct> models;
    private static IList<TreeObejct> models2;
    private static Thread t1;
    private static Thread t2;
    static void Main(string[] args)
    {
      int count = 6;
      Console.WriteLine("生成任务数:"+count+"个");
      models = GetData(count);
      models2 = GetData(count);
      t1 = new Thread(Recursion);
      t2 = new Thread(NotRecursion);
      t1.Name = "递归遍历";
      t2.Name = "非递归遍历";
      t1.Start();
      t2.Start();

      Console.Read();
    }

启动查看执行结果:

C#,查找树形结构数据,C#构建树形结构数据

发现一个问题,递归3s,非递归0s,随后我又进行了更多的测试:

执行时间测试

 

任务个数           递归(ms)               非递归(ms)
6 3 0
6 1 0
6 1 0
101 1 0
101 4 0
101 5 0
1001 196 5
1001 413 1
1001 233 7
5001 4667 5
5001 4645 28
5001 5055 7
10001 StackOverflowException 66
10001 StackOverflowException 81
10001 StackOverflowException 69
50001 - 46
50001 - 47
50001 - 42
100001 - 160
100001 - 133
100001 - 129