剪枝树分支,其中结束节点满足某些条件

时间:2013-04-18 19:37:53

标签: c# linq

我有一个TreeNode课程如下:

public class TreeNode
{
    public enum NodeType { Root,Element, Category}
    public TreeNode()
    {
        Children = new List<TreeNode>();
    }
    public List<TreeNode> Children { get; set; }
    public string Name { get; set; }
    public NodeType Type { get; set; }
}

我有一个BuildTree方法填充树结构,为每个节点设置节点名称和类型(例如,第一个节点将设置为Root Type,子节点可以是Element或Category类型) 。

我正在寻找一种有效的方法(可能使用LINQ)来修剪结束节点类型不是Category类型的树枝。关于如何实现这一点的任何想法?

这是一个直观的例子:

之前

Root
|
|_ NodeA (Element)
|_ Node B (Element)
|  |_ Node B.1 (Category)
|_ Node C (Element)
|  |_ Node C.1 (Element)
|    |_Node C.1.1 (Category)
|_ Node D (Element)
   |_Node D.1 (Element)

Root
|
|_ Node B (Element)
|  |_ Node B.1 (Category)
|_ Node C (Element)
   |_ Node C.1 (Element)
     |_Node C.1.1 (Category)

提前致谢!

3 个答案:

答案 0 :(得分:3)

首先,我们需要描述如何对树进行深度优先聚合:

//seed: leafNode -> accumulate
//func: interiorNode, children accumulates -> accumulate
public static TAccumulate Aggregate<TAccumulate>(
    this TreeNode root,
    Func<TreeNode, TAccumulate> seed,
    Func<TreeNode, List<TAccumulate>, TAccumulate> func)
{
    if (root.Children == null || !root.Children.Any())
        return seed(root);
    return func(root, children.Select(child => child.Aggregate(seed, func)).ToList());
}

然后我们可以使用它来进行修改,例如你要求的修改:

tree.Aggregate(
    leaf => new
    {
        Keep = leaf.NodeType == TreeNode.NodeType.Category,
        Node = leaf
    },
    (node, children) =>
    {
        var removal = new HashSet<TreeNode>(
            children.Where(child => !child.Keep).Select(child => child.Node));
        node.Children.RemoveAll(removal.Contains);
        return new
        {
           Keep = children.Any(child => child.Keep),
           Node = node
        };
    });

这为您提供了一种简洁的声明方式,用于描述您希望应用于树的变换,而无需在变换描述中了解遍历的细节。

答案 1 :(得分:1)

它并不复杂;你只需要对树进行递归遍历。基本情况是节点本身是一个类别。然后只需在每个孩子上调用该函数,并将那些孩子中的类别保留下来。

/// <summary>
/// Removes all child nodes that do not have at least one Category as a child.
/// </summary>
/// <param name="node">The node to alter the children of.</param>
/// <returns>True if there is at least one Category in this subtree</returns>
public static bool RemoveEmptyElements(TreeNode node)
{
    if (node.Type == TreeNode.NodeType.Category)
        return true;
    node.Children = node.Children.Where(child => RemoveEmptyElements(child))
            .ToList();
    return node.Children.Any();
}

答案 2 :(得分:0)

您可以使用下订单来遍历树。当您返回到树的第2级而没有找到类别类型叶。再次从此节点遍历以删除所有以它为根的叶子。