Tree traversal

Home Forums C Programming Tree traversal

This topic contains 1 reply, has 2 voices, and was last updated by  will 10 years, 2 months ago.

  • Author
  • #2041


    I’m trying to create a function in C++ that would make an iterator traverse a tree in the following way: Visit root node first, traverse right subtree, traverse left subtree. I have already created a separate function that would initialize the iterator at the root.

    Below is the function that I have written so far that would traverse the tree assuming that the iterator is already at the root.                               

    The problem I’m having with this function is that once the iterator reaches the end of the right subtree, it will go into an infinite loop. The “n++” makes the iterator go down to the right while the “–n” makes the iterator go up. The iterator goes back and forth between two nodes causing an infinite loop. How can I correct this problem?

  • #3288


    You will need to use this function recursively and mantain the visiting of the nodes. you will need to keep track of all the nodes which have been traversed and on that criteria you will call this dunction. At the moment you are just calling this function from any location and it gets stuck in loop. So in order to break that loop you will need a criteria to break the loop. And that criteria can be fulfilled by using another linked list or a variable which will hold the number of nodes traversed and then compare that variable with the actual number of nodes of the tree.
    Hopefully this answers your question.

You must be logged in to reply to this topic.