在C#中實現二叉樹的插入和刪除操作可以通過定義一個二叉樹節點類和一個二叉樹類來實現。下面是一個簡單的示例代碼:
using System;
public class Node
{
public int data;
public Node left;
public Node right;
public Node(int data)
{
this.data = data;
left = null;
right = null;
}
}
public class BinaryTree
{
private Node root;
public BinaryTree()
{
root = null;
}
public void Insert(int data)
{
root = InsertRec(root, data);
}
private Node InsertRec(Node root, int data)
{
if (root == null)
{
root = new Node(data);
return root;
}
if (data < root.data)
{
root.left = InsertRec(root.left, data);
}
else if (data > root.data)
{
root.right = InsertRec(root.right, data);
}
return root;
}
public void Delete(int data)
{
root = DeleteRec(root, data);
}
private Node DeleteRec(Node root, int data)
{
if (root == null)
{
return root;
}
if (data < root.data)
{
root.left = DeleteRec(root.left, data);
}
else if (data > root.data)
{
root.right = DeleteRec(root.right, data);
}
else
{
if (root.left == null)
{
return root.right;
}
else if (root.right == null)
{
return root.left;
}
root.data = MinValue(root.right);
root.right = DeleteRec(root.right, root.data);
}
return root;
}
private int MinValue(Node root)
{
int minv = root.data;
while (root.left != null)
{
minv = root.left.data;
root = root.left;
}
return minv;
}
}
public class MainClass
{
public static void Main()
{
BinaryTree tree = new BinaryTree();
tree.Insert(50);
tree.Insert(30);
tree.Insert(20);
tree.Insert(40);
tree.Insert(70);
tree.Insert(60);
tree.Insert(80);
Console.WriteLine("Inorder traversal of the given tree");
tree.Inorder();
Console.WriteLine("\nDelete 20");
tree.Delete(20);
Console.WriteLine("Inorder traversal of the modified tree");
tree.Inorder();
Console.WriteLine("\nDelete 30");
tree.Delete(30);
Console.WriteLine("Inorder traversal of the modified tree");
tree.Inorder();
Console.WriteLine("\nDelete 50");
tree.Delete(50);
Console.WriteLine("Inorder traversal of the modified tree");
tree.Inorder();
}
}
在上面的示例代碼中,我們定義了一個Node
類和一個BinaryTree
類來實現二叉樹的插入和刪除操作。Insert
方法用于插入節點,Delete
方法用于刪除節點。我們還實現了一個MinValue
方法來找到指定節點下的最小值節點。在Main
方法中,我們演示了如何使用這些方法來操作二叉樹。