我在C#中做了一个简单的程序来在二叉树中添加一个节点。 我有一个对象字段'根'来保存主父节点。这样每次我添加一个节点时,我都会通过检索父节点中的数据从树中遍历一个节点。对象在没有任何代理的情况下自动更新
这里是我的代码
public class BTNode
{
public int Value { get; set; }
public BTNode Left { get; set; }
public BTNode Right { get; set; }
public BTNode Root { get; set; }
}
public class BinaryTree
{
public BinaryTree()
{
size = 0;
Root = null; //To hold the main Parent Node
}
int size;
object Root;
public void AddNode(int value)
{
BTNode NewNode = new BTNode();
if (Root != null)
{
NewNode = (BTNode)Root; //If tree exists, Get the Root Node
}
while (NewNode.Root != null)
{
if (value < NewNode.Value)
{
NewNode.Root = NewNode.Left;
}
else if (value > NewNode.Value)
{
NewNode.Root = NewNode.Right;
}
}
size++;
NewNode.Value = value; //OBJECT 'ROOT' GETTING UPDATED AT THIS POINT
NewNode.Root = NewNode; //self pointer
NewNode.Left = null;
NewNode.Right = null;
if (size == 1)
{
Root = (object) NewNode; //if this is the Parent Node(First Node)
} //then update the Root to be the parent Node
}
}
我想抱着二叉树的唯一父节点“根”。我只想要执行的最后一行时,大小= 1,即如果它的第一个节点的树,但无论我做什么,Root都会针对每个节点进行更新。我正在努力知道为什么会发生这种情况,请帮助我。我在这里错过了任何的合作,逻辑。
当你说'NewNode.Root = NewNode.Left;'你不是重新分配每个节点的'Root'吗?我认为相反,你只是想说'NewNode = NewNode.Left;' – mellamokb 2012-07-24 13:46:39
我实际上创建了NewNode.Root,以便我可以将它用作参考或指向其子节点的指针。我想我可以像你说的那样编码。我不需要BTNode类中的Root属性。谢谢。 – Rasm 2012-07-24 15:21:54