在任意树中查找特定元素

时间:2016-08-16 05:11:14

标签: c# oop tree traversal

在遍历树DFS时,我一直在努力寻找元素。下面是我的树实现。它由另一个类的对象填充。我想要的是在给定值的树中找到一个元素,并且在尝试这样做时我遇到了一些实际问题。有没有办法可以为节点添加一些Key引用,然后搜索所有节点以获取此引用?我真的很感激帮助! :) 谢谢。

This site can’t be reached - server DNS address could not be found

1 个答案:

答案 0 :(得分:0)

从代码中可以看出它是如何被填充的,但是我已经对代码进行了一些调整并尝试清理它以便我们可以实现填充和搜索树。我添加了一些公共属性和方法。

public class Tree<T>
{
    // The root of the tree
    private TreeNode<T> root;


    public Tree(T value)
    {
        if (value == null)
        {
            throw new ArgumentNullException(nameof(value), "Cannot insert null value!");
        }

        root = new TreeNode<T>(value, null);
    }


    public Tree(T value, params Tree<T>[] children)
        : this(value)
    {
        foreach (Tree<T> child in children)
        {
            root.AddChild(child.root);
        }
    }

    public TreeNode<T> Root => root;

    public TreeNode<T> FindByValue(T value) => Root.FindByValue(value);

}


public class TreeNode<T>
{
    public TreeNode(T value, TreeNode<T> parent)
    {
        this.parent = parent;
        if (value == null)
        {
            throw new ArgumentNullException(nameof(parent), "Cannot insert null value!");
        }
        this.value = value;
        children = new List<TreeNode<T>>();
    }


    private T value;
    public TreeNode<T> parent;
    private List<TreeNode<T>> children;


    public T Value
    {
        get { return value; }
        set { this.value = value; }
    }
    public int ChildrenCount => children.Count;

    public TreeNode<T> AddChild(TreeNode<T> child)
    {
        children.Add(child);
        return child;
    }

    public TreeNode<T> AddChild(T value) => AddChild(new TreeNode<T>(value, this));

    public TreeNode<T> FindByValue(T value)
    {
        if (value.Equals(Value))
            return this;

        foreach (var child in children)
        {
            var match = child.FindByValue(value);
            if (match != null)
                return match;
        }
        return null;
    }
}

样本用法:

//create a new tree..
var tree = new Tree<string>("root-item");

//populate the tree with 10 items with 10 sub items
for (int i = 0; i < 10; i++)
{
    var node = tree.Root.AddChild($"item-{i}");
    for (int w = 0; w < 10; w++)
    {
        node.AddChild($"sub-item-{i}-{w}");
    }
}

//find the root node
var findNode = tree.Root.FindByValue("root-item");

//find a sub node item
findNode = tree.FindByValue("sub-item-1-1");