在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
方法中,我们演示了如何使用这些方法来操作二叉树。