我在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