我想寫一個函數在C#,它允許我交換二叉樹的兩個節點,但它不能按預期方式工作。在二叉樹中交換節點
這裏是類與交換方法:
class Node
{
public int value;
public Node parent { get; set; }
public Node left { get; set; }
public Node right { get; set; }
public Node addLeft(int value)
{
this.left = new Node(value);
this.left.parent = this;
this.left.left = null;
this.left.right = null;
return this.left;
}
public Node addRight(int value)
{
this.right = new Node(value);
this.right.parent = this;
this.right.left = null;
this.right.right = null;
return this.right;
}
public Node(int value)
{
this.value = value;
this.parent = null;
this.left = null;
this.right = null;
}
public Node getRoot()
{
Node n = this;
while(n.parent!=null)
{
n = n.parent;
}
return n;
}
public static void swap(ref Node n1,ref Node n2)
{
//updating references of n1 and n2 parents
if(n1.Equals(n1.parent.left)) //n1 is a left child
{
n1.parent.left = n2;
}
else if(n1.Equals(n1.parent.right)) //n1 is a right child
{
n1.parent.right = n2;
}
else
{
throw new Exception("Something is wrong");
}
if (n2.Equals(n2.parent.left)) //n2 is a left child
{
n2.parent.left = n1;
}
else if (n2.Equals(n2.parent.right)) //n2 is a right child
{
n2.parent.right = n1;
}
else
{
throw new Exception("Something is wrong");
}
//updating references of n1 and n2 childs
if(n1.left != null)
{
n1.left.parent = n2;
}
if (n1.right != null)
{
n1.right.parent = n2;
}
if (n2.left != null)
{
n2.left.parent = n1;
}
if (n2.right != null)
{
n2.right.parent = n1;
}
//Swapping n1 and n2 references
Node t_p = n1.parent;
Node t_l = n1.left;
Node t_r = n1.right;
n1.parent = n2.parent;
n1.left = n2.left;
n1.right = n2.right;
n2.parent = t_p;
n2.left = t_l;
n2.right = t_r;
}
}
這裏是我的主要功能:
static void Main(string[] args)
{
Node root = new Node(10);
Node a = root.addLeft(1);
Node b = root.addRight(2);
Node c = a.addLeft(3);
Node d = a.addRight(4);
Node e = b.addLeft(5);
Node f = b.addRight(6);
Node g = d.addLeft(7);
Node h = d.addRight(8);
Node.swap(ref a,ref d);
Console.WriteLine("Value is: " + root.left.value);
Console.WriteLine("Value is: " + root.left.right.value);
Console.WriteLine("Root: " + a.getRoot().value);
Console.WriteLine("Root: " + d.getRoot().value);
Console.Read();
}
的輸出上面的代碼是:
Value is: 4
Value is: 1
它掛在第二個Console.WriteLine後,我不明白爲什麼。你能告訴我我做錯了什麼嗎?
編輯:
如果我嘗試將節點多次交換時,「有些事情不對」拋出異常。
你爲什麼要用'ref'將''''交給''swap'? –
它可能已經掛起,因爲getRoot沒有返回,這意味着你可能已經搞亂了變化的父母。 – lared
如果您在問題中確切定義了交換應實現的功能,它也將有所幫助。我*想*你正試圖交換節點本身而不是整個子樹。 –