在C#中,可以通過定義一個二叉樹類來實現動態數據集合。以下是一個簡單的C#二叉樹實現示例:
using System;
public class Node
{
public int value;
public Node left;
public Node right;
public Node(int value)
{
this.value = value;
this.left = null;
this.right = null;
}
}
public class BinaryTree
{
public Node root;
public BinaryTree()
{
this.root = null;
}
public void Insert(int value)
{
Node newNode = new Node(value);
if (this.root == null)
{
this.root = newNode;
}
else
{
InsertRecursively(this.root, newNode);
}
}
private void InsertRecursively(Node currentNode, Node newNode)
{
if (newNode.value < currentNode.value)
{
if (currentNode.left == null)
{
currentNode.left = newNode;
}
else
{
InsertRecursively(currentNode.left, newNode);
}
}
else
{
if (currentNode.right == null)
{
currentNode.right = newNode;
}
else
{
InsertRecursively(currentNode.right, newNode);
}
}
}
public void TraverseInOrder(Node node)
{
if (node != null)
{
TraverseInOrder(node.left);
Console.Write(node.value + " ");
TraverseInOrder(node.right);
}
}
public void TraversePreOrder(Node node)
{
if (node != null)
{
Console.Write(node.value + " ");
TraversePreOrder(node.left);
TraversePreOrder(node.right);
}
}
public void TraversePostOrder(Node node)
{
if (node != null)
{
TraversePostOrder(node.left);
TraversePostOrder(node.right);
Console.Write(node.value + " ");
}
}
public static void Main()
{
BinaryTree binaryTree = new BinaryTree();
binaryTree.Insert(10);
binaryTree.Insert(5);
binaryTree.Insert(15);
binaryTree.Insert(7);
binaryTree.Insert(12);
Console.WriteLine("In-order traversal:");
binaryTree.TraverseInOrder(binaryTree.root);
Console.WriteLine("\nPre-order traversal:");
binaryTree.TraversePreOrder(binaryTree.root);
Console.WriteLine("\nPost-order traversal:");
binaryTree.TraversePostOrder(binaryTree.root);
}
}
在以上示例中,定義了一個Node
類來表示二叉樹的節點,以及一個BinaryTree
類來實現二叉樹的操作。可以使用Insert
方法來插入新節點,以及使用TraverseInOrder
、TraversePreOrder
和TraversePostOrder
方法來遍歷二叉樹。可以根據需要擴展該實現,以滿足特定的需求。