January 22nd, 2013, 03:56 PM
How to search a tree(postorder) in C
I write a function to search a tree, and find out the node suitable and store them in an array. It is in postorder.
But it can't work. Is there anything wrong in my code?
void search_for_node(node *root, node *list) // root is the top of a tree, and the array list is used to store the node that is suitable and the space is enough
if (root == NULL)
for(j=0; j<root->num_children; j++) //num_children is a member of node structure indicating the number of children
if (root->type == ID)
list[num_for++] = root; //num_for is a global variable counting the number of nodes suitable
Thanks in advance!
January 22nd, 2013, 04:08 PM
You need to post something more informative than "it doesn't work".
> list[num_for++] = root;
What is num_for ?
How is list allocated?
How do you prevent array overrun?
If you comment this out, does the function traverse the tree without doing anything (and without crashing)?
Have you run the code in the debugger?
January 22nd, 2013, 08:43 PM
num_for is a global variable counting the number of nodes suitable. I have allocated the array enough space.
Originally Posted by salem
I have used gdb to debug it, and found that the function will not go to the leaf, but I think the logic of my code is right.
Now, I am confused.
Is the function right just in terms of the basic logic?
January 22nd, 2013, 10:30 PM
It can work!
Thank you for attention!!! :)