在树形数据结构中,逐级显示树节点
问题:如何逐级显示树节点?您能给我时间和空间有效的解决方案吗?
示例:
A
/ \
B C
/ \ / \
D E F G
void PrintTree(struct tree *root);
输出: 您必须逐级打印树节点
A
B C
D E F G
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 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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您感觉很野蛮,并且想简单地思考一下您所处的水平...
您将需要:
所以,从 root 开始。
将其子级添加到第一个队列中。
穿过他们,将他们的孩子放到第二个队列中。
切换到第二个队列,单步执行,将其子级推入第一个队列。
上蜡,脱蜡。
实际上,它只是同一想法(广度优先搜索或扫描)的轻微扩展,值得将其作为一种模式进行思考,因为它适用于各种数据结构。事实上,几乎所有东西都是树或特里树,还有一些不是!
If you're feeling brutish, and want to think very simply about the level you are at...
You will need:
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!
为了节省空间和时间:
http://thecodecracker.com/c-programming/ bfs 和 dfs/
To save space and time on SO:
http://thecodecracker.com/c-programming/bfs-and-dfs/
这种访问称为广度优先或层次顺序。您可以在此处查看其他信息。
基本上,您
类推。这应该可以使用 FIFO 结构轻松实现:
This kind of visit is called Breadth-first or Level Order. You can see additional infos here.
Basically you
This should be achieved easily with a FIFO structure: