recursive inorder bst

hello
i want to write an inorder function that takes all the nodes from the bst and stores them in an array (given as parameter to function) but i want to do it using recursion.

it works with the following code but it works only once because of the static pointer temp.the second time temp keeps the value stored before.


1
2
3
4
5
6
7
8
9
10
11
void BinaryTree::PrivateInOrder( int* arr , TreeNode* root ) const
{
	static int* temp = arr;
	if( root )
	{
		PrivateInOrder( NULL , root->leftChildptr );
		*temp = root->data;
		temp++;
		PrivateInOrder( NULL , root->rightChildptr );
	}
}


1)can i use a static variable or a variable that acts like static in order to set the temp to arr every time i call the function but when it call itself it can keep the previous value.
thanks
Instead of using the static variable (that often leads to surprising results) use an index, like so:

1
2
3
4
5
6
7
8
9
10
11
12
int BinaryTree::PrivateInOrder( int* arr, int idx , TreeNode* root ) const
{
	int res = idx;
	if( root )
	{
		arr[res] = root->data;
		res++;
		res = PrivateInOrder( arr , res , root->leftChildptr );
		res = PrivateInOrder( arr ,  res , root->rightChildptr );
	}
	return res;
}


If I get it right...
yes it works.are there any tricks about recursion i should know because i spent hours yesterday and all i got was the code with the static.and yet you did it in 2 minutes.whats the secret?
Well, no tricks no secrets just experience
Topic archived. No new replies allowed.