Search code examples
c++treenodes

Forest of tree nodes C++?


Hey, I am trying to create a "forest" of tree nodes. A user will input two forests.. For example,
Forest1 :
a
_ _b
c

where b is a child tree/node of a.
Forest2:
d
e
_ _f
_ _ _ _g
_ _h

where d is a parent, e is the parent of f and h, f is the parent of g. f and h are siblings.

Anyway, I have two questions that I've been stuck on for awhile:
What is the best way to get this input (from a unix system?) line by line?
And, what is the best way to traverse this in order to get parents and children.
Any other tips are appreciated also, thanks!!


Solution

  • It doesn't really matter too much on what kind of system you're on, but yes, process it line by line using an ifstream. There really isn't a "best way" to traverse this I don't think, as it is a text file and someone can pass you a txt file formatted in any weird way; so you should consider that and try to handle all cases as best as you can.

    So, let's try stepping through how you can do this.

    You're in a loop processing this line by line, your current node is set to NULL as a parent hasn't been processed yet. Read in the line and look for an underscore at the beginning of the string; if parent is null, well then wee have a line that can't be processed, so skip it. If the first character isn't an underscore, set this to the current parent node and move on to the next part of the loop. If there is an underscore and the current parent isn't null, then iterate through the remaining number of underscores and iterate down the children of nodes inside of the parent.

    Actually, I just had a better idea, but this will give you something to think about at least. Cheers, let me know what you come up with.