#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2012
    Posts
    17
    Rep Power
    0

    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.
    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
    {
    	int j;
    	if (root == NULL)
    		return;
    	
    	
    	for(j=0; j<root->num_children; j++) //num_children is a member of node structure indicating the number of children 
    		search_for_node(root->children[j], list); 
    	if (root->type == ID)
    	list[num_for++] = root; //num_for is a global variable counting the number of nodes suitable
    
    	
    	
    }
    But it can't work. Is there anything wrong in my code?
    Thanks in advance!
  2. #2
  3. Contributed User
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Jun 2005
    Posts
    4,379
    Rep Power
    1871
    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?
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2012
    Posts
    17
    Rep Power
    0
    Originally Posted by salem
    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?
    num_for is a global variable counting the number of nodes suitable. I have allocated the array enough space.
    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?
  6. #4
  7. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2012
    Posts
    17
    Rep Power
    0
    It can work!
    Thank you for attention!!! :)

IMN logo majestic logo threadwatch logo seochat tools logo