【问题标题】:Better performance and readability for a C# tree [closed]C# 树的更好的性能和可读性[关闭]
【发布时间】:2021-08-23 07:44:06
【问题描述】:

我想在 C# 中创建一棵树,这棵树是二叉树,所以它会有当前节点和另外 2 个节点,NodeYes 和 NodeNot。

就可读性和性能而言,这两种表示中哪一种更好?

 public class Tree_1
    {
        public No NodeActual { get; set; }
        public No NodeYes { get; set; }
        public No NodeNot { get; set; }
    }


    public class Tree_2
    {
        public No NodeActual { get; set; }
        List<No> NodeChidrens { get; set; }
        // position 1 - no
        // position 1 - yes
    }

【问题讨论】:

  • 我是第一个
  • 你好 b0neng4,为什么?

标签: c# tree binary-tree


【解决方案1】:

两者都不是。你只需要

public class TreeNode 
{ 
    public TreeNode Left; 
    public TreeNode Right; 
    public object NodeData; 
    public void SomeMethod() 
    { 
         DoSomething(Left); 
         DoSomething(Right);
         DoSomething(this); // if you want to reference the current node
         // Left.NodeData, Right.NodeData and this.NodeData or simply NodeData 
    }
}

要跟踪树,只需保留根节点

public class Tree
{
    public TreeNode Root;
}

List&lt;&gt; 的想法非常适合推广到 n 叉树(最多 n 个子节点),但对于二叉树来说没有意义,并且可能会因额外的索引复杂性而导致(可忽略不计的)性能损失。

研究递归 - 遍历树的非常强大、直观的方法 - 有一些危险(其中一个是反对它的宗教;-) 我的建议:学习它,了解它的局限性,等它成为你的朋友你也会知道什么时候该努力不使用它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-19
    • 1970-01-01
    • 2012-09-28
    • 2013-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多