【发布时间】:2011-05-21 22:46:54
【问题描述】:
我有一个非常奇怪的问题。基本上,我创建了一个名为 TreeNode 的类,它代表树中的一个节点。然后我通过将所有节点添加到列表来创建树。
class TreeNode
{
private TreeNode parent, lChild, rChild;
private int key, val;
public int Key
{
get { return key; }
set { key = value; }
}
public int Val
{
get { return val; }
set { val = value; }
}
public TreeNode Parent
{
get { return parent; }
set { parent = value; }
}
public TreeNode LChild
{
get { return lChild; }
}
public TreeNode RChild
{
get { return rChild; }
}
public TreeNode(int k, int v)
{
key = k;
val = v;
}
public void SetChild(TreeNode leftChild, TreeNode rightChild)
{
this.lChild = leftChild;
this.rChild = rightChild;
}
public bool isLeaf()
{
if (this.lChild == null && this.rChild == null)
{
return true;
} else
{
return false;
}
}
public bool isParent()
{
if (this.parent == null)
{
return true;
}
else
{
return false;
}
}
public void SetParent(TreeNode Parent)
{
this.parent = Parent;
}
}
因此,如果我在创建树之后放置一个断点并将鼠标悬停在 Visual Studio 中的列表上,我可以看到树的结构 - 所有引用从根到叶都完美地工作。
如果我执行以下操作:
TreeNode test = newTree[newTree.Count - 1];
请注意:
private List<TreeNode> newTree = new List<TreeNode>();
它返回根节点 - 再次悬停我可以向下一级(即左孩子或右孩子),但这些孩子之后没有任何对他们孩子的引用。
我想知道由于测试节点不是列表的一部分,我是否丢失了对列表中其他节点的内存引用?
任何帮助将不胜感激。
谢谢 汤姆
【问题讨论】: