[英]Remove from binary tree C#
嗨,我在從C#中的二叉樹中刪除時遇到了一個小問題。 我不知道為什么,但是這段代碼無法正常工作(調用remove方法后我的樹沒有改變)。 這是我的代碼:
public class BinaryTree<T>
{
public BinaryTree<T> Left, Right;
public T Data;
public BinaryTree()
{
this.Left = null;
this.Right = null;
}
}
public BinaryTree<T> FindNode(T value,ref BinaryTree<T> myTree)
{
if (myTree == null)
return null;
else
{
int result = Comparer<T>.Default.Compare(value, myTree.Data);
if (result == 0)
return myTree;
else if (result > 0)
return FindNode(value, ref myTree.Right);
else if (result < 0)
return FindNode(value, ref myTree.Left);
}
return myTree;
}
public void RemoveValue(T value,ref BinaryTree<T> myTree)
{
BinaryTree<T> helper = new BinaryTree<T>();
BinaryTree<T> MyTree = myTree;
if (MyTree == null) return;
MyTree =FindNode(value,ref MyTree);
if (MyTree.Left == null || MyTree.Right == null)
helper = MyTree;
else
{
helper = MyTree.Left;
while (helper.Right!=null)
helper = helper.Right;
MyTree.Data = helper.Data;
}
if (helper.Left == null)
helper = helper.Right;
else
helper = helper.Left;
}
BinaryTree表示樹中的每個節點。
這是對您的代碼的一些小整理,其中包含有關我認為RemoveValue
應該如何工作的建議。 我由您決定完成實施。
public class BinaryTree<T>
{
public T Data;
public BinaryTree<T> Left, Right;
public BinaryTree()
{
this.Left = null;
this.Right = null;
}
public static BinaryTree<T> FindNode(T value, BinaryTree<T> myTree)
{
if (myTree == null)
return null;
else
{
int result = Comparer<T>.Default.Compare(value, myTree.Data);
if (result == 0)
return myTree;
else if (result > 0)
return FindNode(value, myTree.Right);
else if (result < 0)
return FindNode(value, myTree.Left);
}
return myTree;
}
public static void RemoveValue(T value, ref BinaryTree<T> myTree)
{
if (myTree == null)
return;
BinaryTree<T> treeNodeToRemove = FindNode(value, myTree);
// First case: The node to remove has a single subtree
if(treeNodeToRemove.Left == null ^ treeNodeToRemove.Right == null)
{
// We need to change the Left||Right reference of our parent to us...
}
// Second case: Both subtrees are null
else if (treeNodeToRemove.Left == null && treeNodeToRemove.Right == null)
{
// We need to change the reference of our parent to null
}
// Third case: Both subtrees are full
else
{
// ...
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.