如何创建二叉树 [英] How to create a binary tree
问题描述
我并不是二叉搜索树。
例如
如果我将值1,2,3,4,5插入到二进制搜索树的顺序遍历将给出
1,2,3,4,5作为输出。
for example, if I insert values 1,2,3,4,5 in to a binary search tree the inorder traversal will give 1,2,3,4,5 as output.
但是如果我将相同的值插入二进制树,无序遍历应该给出
4,2,5,1,3作为输出。
but if I insert the same values in to a binary tree, the inorder traversal should give 4,2,5,1,3 as output.
可以使用动态数组创建二叉树,其中每个元素在索引n中,
2n + 1和2n + 2分别表示其左和右子。
Binary tree can be created using dynamic arrays in which for each element in index n, 2n+1 and 2n+2 represents its left and right childs respectively.
所以表示和级别遍历在这里非常容易。
so representation and level order traversal is very easy here.
但我认为,按顺序,订单后,预订很困难。
but I think, in-order,post-order,pre-order is difficult.
我的问题是如何创建一个二叉树像二叉搜索树。
ie。
有一个树类,它包含数据,左和右指针而不是数组。
,以便我们可以递归地执行遍历。
my question is how can we create a binary tree like a binary search tree. ie. have a tree class which contains data, left and right pointers instead of arrays. so that we can recursively do traversal.
推荐答案
如果我正确理解你,你想创建一个二叉树从数组
If I understand you correctly, you want to create a binary tree from an array
int[] values = new int[] {1, 2, 3, 4, 5};
BinaryTree tree = new BinaryTree(values);
这应该预先填充值为1到5的二叉树,如下所示:
this should prepopulate the binary tree with the values 1 - 5 as follows:
1
/ \
2 3
/ \
4 5
这可以使用以下类完成:
this can be done using the following class:
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);
}
}
}
这篇关于如何创建二叉树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!