我不是说二叉搜索树。
例如, 如果我将值 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/