【发布时间】:2016-08-16 05:11:14
【问题描述】:
在遍历树 DFS 时,我一直在努力寻找元素。下面是我的树实现。它由另一个类的对象填充。我想要的是通过给定的值在树中找到一个元素,我在尝试这样做时遇到了一些实际问题。有没有办法可以向节点添加一些 Key 引用,然后在所有节点中搜索该引用?我非常感谢您的帮助! :) 谢谢。
public class TreeNode<T>
{
private T value;
private bool hasParent;
public TreeNode<T> parent;
private List<TreeNode<T>> children;
public TreeNode(T value, TreeNode<T> parent)
{
this.parent = parent;
if (value == null)
{
throw new ArgumentNullException(
"Cannot insert null value!");
}
this.value = value;
this.children = new List<TreeNode<T>>();
}
public T Value
{
get
{
return this.value;
}
set
{
this.value = value;
}
}
public int ChildrenCount
{
get
{
return this.children.Count;
}
}
public class Tree<T>
{
// The root of the tree
private TreeNode<T> root;
public Tree(T value)
{
if (value == null)
{
throw new ArgumentNullException(
"Cannot insert null value!");
}
this.root = new TreeNode<T>(value,null);
}
public Tree(T value, params Tree<T>[] children)
: this(value)
{
foreach (Tree<T> child in children)
{
this.root.AddChild(child.root);
}
}
【问题讨论】: