Question: how can we display tree nodes level by level ?. could you please give me time and space efficient solution .
Example :
A
/ \
B C
/ \ / \
D开发者_C百科 E F G
void PrintTree(struct tree *root);
Output: You have to print tree nodes level by level
A
B C
D E F G
If you're feeling brutish, and want to think very simply about the level you are at...
You will need:
- Two queues
- A slight twist on Jack's approach
So, start with root.
Tack its children onto the first queue.
Step through them, tacking their children onto the second queue as you go.
Switch to the second queue, step through, pushing their children onto the first queue.
Wax on, wax off.
Really it's just a slight expansion of the same idea, the breadth first search or sweep, which is worth thinking about as a pattern, since it applies to a variety of data structures. Almost anything that's a tree or trie, and a few things that aren't, in fact!
To save space and time on SO:
http://thecodecracker.com/c-programming/bfs-and-dfs/
This kind of visit is called Breadth-first or Level Order. You can see additional infos here.
Basically you
- first visit the current node
- then all the children of that node
- then all the children of every children and so on
This should be achieved easily with a FIFO structure:
- push the root
- until queue is empty
- take first element, visit it, and push all its children to the end of the queue
- repeat
精彩评论