温馨提示×

c#二叉树如何实现动态数据集合

c#
小樊
85
2024-07-26 02:49:14
栏目: 编程语言

在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方法来插入新节点,以及使用TraverseInOrderTraversePreOrderTraversePostOrder方法来遍历二叉树。可以根据需要扩展该实现,以满足特定的需求。

0