[英]I have a binary search tree and I want to copy the nodes to an array with inorder (recursive function)
Hi I have a BST binary search tree 嗨,我有一个BST二叉搜索树
typedef struct Treenode *SearchTree;
struct Treenode
{
int Element;
SearchTree Left;
SearchTree Right;
};
and I want to create a function 我想创建一个函数
FillArray(int sizeoftree, tree, int array[])
And I want to use an array and copy the nodes of the tree in the array. 我想使用一个数组并复制数组中树的节点。 How can I do this?
我怎样才能做到这一点? the following code does not work.
以下代码不起作用。 I tried:
我试过了:
int FillArray(int a,SearchTree T,int arr[])
{
if (T==NULL)
{
return 0;
}
else
{
FillArray(a,T->Left,arr);
arr[a]=T->Element;
a++;
FillArray(a,T->Right,arr);
}
}
Your problem is that your function FillArray
is only modifying its argument a
, which is not visible to its caller, since argument passing in C is by value. 你的问题是你的函数
FillArray
只修改它的参数a
,它的调用者看不到它,因为在C中传递的参数是值。 You will need some way to have the recursive calls tell the spot in arr
to which to add the elements. 你需要一些方法让递归调用告诉
arr
中要添加元素的位置。 One simple way to do this would be to add a parameter, say, index
that gives the first index in arr
to which to add an element, and return from FillArray
the number of elements added so that you can properly update index
after calling FillArray
recursively and to return the total number of elements added. 一个简单的方法是添加一个参数,比如,
index
给arr
的第一个索引添加一个元素,并从FillArray
返回添加的元素数,这样你就可以在递归调用FillArray
后正确更新index
并返回添加的元素总数。
FillArray
is declared as returning an int
, but you do not have a return value in the else
case. FillArray
被声明为返回一个int
,但在else
情况下你没有返回值。
You can use this return value to denote the number of elements filled in; 您可以使用此返回值来表示填充的元素数量; this way, you know where to place the current element in-order.
这样,您就知道将当前元素按顺序放在何处。
int FillArray(int a, SearchTree T, int arr[]) {
int count = 0;
if (T) {
count += FillArray(a, T->Left, arr);
arr[a + count++] = T->Element;
count += FillArray(a + count, T->Right, arr);
}
return count;
}
得通过引用传递
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.