c# - 如何创建二叉树

标签 c# data-structures binary-tree

我不是说二叉搜索树。

例如, 如果我将值 1,2,3,4,5 插入到二叉搜索树中,中序遍历将给出 1,2,3,4,5 作为输出。

但是如果我将相同的值插入到二叉树中,中序遍历应该给出 4,2,5,1,3 作为输出。

可以使用动态数组创建二叉树,其中对于索引 n 中的每个元素, 2n+1和2n+2分别代表它的左右 child 。

因此这里的表示和层次顺序遍历非常容易。

但是我觉得,in-order,post-order,pre-order是很难的。

我的问题是我们如何创建像二叉搜索树一样的二叉树。 IE。 有一个树类,其中包含数据、左指针和右指针而不是数组。 以便我们可以递归地进行遍历。

最佳答案

如果我没理解错的话,你想从一个数组创建一个二叉树

int[] values = new int[] {1, 2, 3, 4, 5};
BinaryTree tree = new BinaryTree(values);

这应该使用值 1 - 5 预填充二叉树,如下所示:

    1
   / \
  2   3
 / \
4   5

这可以使用下面的类来完成:

class BinaryTree
{
    int value;
    BinaryTree left;
    BinaryTree right;

    public BinaryTree(int[] values) : this(values, 0) {}

    BinaryTree(int[] values, int index)
    {
        Load(this, values, index);
    }

    void Load(BinaryTree tree, int[] values, int index)
    {
        this.value = values[index];
        if (index * 2 + 1 < values.Length)
        {
            this.left = new BinaryTree(values, index * 2 + 1);
        }
        if (index * 2 + 2 < values.Length)
        {
            this.right = new BinaryTree(values, index * 2 + 2);
        }
    }
}

关于c# - 如何创建二叉树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/828398/

相关文章:

c# - 如何在按下按钮后刷新datagridview

python - 如何在每次创建页面时生成一定长度的随机 url?

c++ - 数字与数字数组的差之和

c++ - 二叉树只添加到根

C 错误解引用指向不完整类型二叉树的指针

c# - 如何禁止编辑文本框?

c# - FCM - 重新调试应用程序后发送消息时出现 Android Xamarin NotRegistered 错误

c# - 从 .NET 3.5 迁移到 .NET 4.0 后应用程序崩溃

search - 在AVL树中找到两个数字之间的最小间隔

c - c中存储任何数据类型的二叉树