简体   繁体   中英

BST In-Order Traversal Using Recursion

I used the search function, and while I found some similar threads I did not find one that exactly covered my issue.

I am attempting to do a look up of a BST using recursion and an in-order traversal , so I want to keep track of the position of the elements.

I have the following code, but it is not doing what I want it to do. It is doing the correct traversal, but the position is not correct.

void startProces(int x)
{
void inOrder(x,*n,*Position)
}

void inOrder(int x, Node *n, int *Position)
{
    int counter = *Position;
    counter++;
    Position = &counter;
}

This is a homework assignment, so please avoid giving me a direct solution. Also please avoid giving me a suggestion that involve having to rewrite the function parameters as I'm locked in. I would appreciate insight on why my position value is not increment properly. I know that my function currently isn't doing anything once it finds the value. I was planning on implementing that once I figured out this issue.

Clarification : I have an insert function, not shown here. If I insert the nodes (15,5,3,12,10,13,6,7,16,20,18,23) I get the in-order traversal (3,5,6,7,10,12,13,15,16,18,20,23). I want this to correspond to (1,2,3,4,5,6,7,8,9,10,11,12). Eventually when I run something like startProcess(10), I want inOrder to print 5.

Your code copies a variable on the stack and passes the address of that variable. So, for each child node, the value will always be the parent node's value plus one, instead of the previously traversed node's value plus one.

Specifically, this line copies it...

int counter = *Position;

The variable Position is a pointer, where counter is a local variable. The pointer points to the address you give it using & . Every time you call inOrder , it creates a new counter variable that's scoped to that function call.

So, this line...

Position = &counter;

sets the pointer to the counter instance in the above function call. All you need to do is pass a pointer to one specific instance instead of the copies.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM