c# - 从父子节点集合中查找死节点

标签 c# algorithm linq

我有一组具有父子关系的自定义节点。每个节点可以是复合类型(其中有其他子节点)或简单类型(叶级节点)

我想写一个函数来给我所有死节点的列表。 例如这里是节点集合

enter image description here

基于上述情况,p2、p3、p8、p9、p10、p6、c1 是死节点(因为在它们的层次结构中没有任何简单节点)

我需要一个函数作为

private List<NodeEntity> GetDeadNodes(List<NodeEntity> originalList) 

这是拥有原始列表的函数

private List<NodeEntity> GetOriginalList()
{
    var list = new List<NodeEntity>()
    {
        new NodeEntity() {Code = "P1", ParentCode = "001", Type = NodeType.Composite},
        new NodeEntity() {Code = "C1", ParentCode = "001", Type = NodeType.Composite},
        new NodeEntity() {Code = "P2", ParentCode = "P1", Type = NodeType.Composite},
        new NodeEntity() {Code = "P3", ParentCode = "P2", Type = NodeType.Composite},
        new NodeEntity() {Code = "P8", ParentCode = "P3", Type = NodeType.Composite},
        new NodeEntity() {Code = "P9", ParentCode = "P3", Type = NodeType.Composite},
        new NodeEntity() {Code = "P4", ParentCode = "P1", Type = NodeType.Composite},
        new NodeEntity() {Code = "L3", ParentCode = "P1",  Type = NodeType.Simple},
        new NodeEntity() {Code = "P6", ParentCode = "P1",  Type = NodeType.Composite},
        new NodeEntity() {Code = "P10", ParentCode = "P4",  Type = NodeType.Composite},
        new NodeEntity() {Code = "L2", ParentCode = "P4",  Type = NodeType.Simple},
        new NodeEntity() {Code = "P5", ParentCode = "P4",  Type = NodeType.Composite},
        new NodeEntity() {Code = "L1", ParentCode = "P5",  Type = NodeType.Simple}
    };
    return list;
}

最佳答案

您可以从每个简单节点向上执行简单扫描,以收集要保留的所有节点(伪代码):

put Simple nodes in a Set

while node in Set
  add node to a 'seen' list
  add parent to Set

dead nodes = all nodes except 'seen' nodes

关于c# - 从父子节点集合中查找死节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45801336/

相关文章:

c#:Enumerable 类中的 Where()、OrderBy() 和 Select() 不应该采用委托(delegate)类型、lambda 表达式或匿名类型作为参数

c# - 确定一个数字是否在指定的一组范围内

c# - 通过 WPF MVVM 中不断刷新的存储库持久化 EF 更改

c# - C# 将对象转换为二维数组

将单组行和列分解为 n 个随机行和随机列的矩形片段的算法,随机重叠

algorithm - 排序算法 : Big text file with variable-length lines (comma-separated values)

C++ - 如何有效地找出 vector 中的任何字符串是否可以从一组字母中组装出来

c# - 如何在 View 模型中存储 linq 查询结果

c# - 具有分组依据的 Linq 查询

具有模糊背景的 C# 对话框窗体