C#树的更好的性能和可读性
Better performance and readability for a C# tree
我想在 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
}
都没有。你只需要
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<>
如果泛化到 n 元树(最多 n 个子节点),这个想法很好,但是二叉树没有意义,并且可能会因额外的索引复杂性而带来(可忽略的)性能损失.
研究递归 - 非常强大、直观的遍历树的方法 - 有一些危险(其中之一是鼓吹反对它的宗教;-)我的建议:学习它,了解它的局限性以及它成为的时间你的朋友你也会知道什么时候努力不使用它。
我想在 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
}
都没有。你只需要
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<>
如果泛化到 n 元树(最多 n 个子节点),这个想法很好,但是二叉树没有意义,并且可能会因额外的索引复杂性而带来(可忽略的)性能损失.
研究递归 - 非常强大、直观的遍历树的方法 - 有一些危险(其中之一是鼓吹反对它的宗教;-)我的建议:学习它,了解它的局限性以及它成为的时间你的朋友你也会知道什么时候努力不使用它。