在树形数据结构中,逐级显示树节点

发布于 2024-10-04 02:20:52 字数 276 浏览 0 评论 0原文

问题:如何逐级显示树节点?您能给我时间和空间有效的解决方案吗?

示例:

    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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

你げ笑在眉眼 2024-10-11 02:20:52

如果您感觉很野蛮,并且想简单地思考一下您所处的水平...
您将需要:

  • 两个队列
  • 对 Jack 的方法稍有改动

所以,从 root 开始。
将其子级添加到第一个队列中。
穿过他们,将他们的孩子放到第二个队列中。
切换到第二个队列,单步执行,将其子级推入第一个队列。
上蜡,脱蜡。

实际上,它只是同一想法(广度优先搜索或扫描)的轻微扩展,值得将其作为一种模式进行思考,因为它适用于各种数据结构。事实上,几乎所有东西都是树或特里树,还有一些不是!

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!

忆伤 2024-10-11 02:20:52

这种访问称为广度优先层次顺序。您可以在此处查看其他信息。

基本上,您

  • 首先访问当前节点
  • ,然后访问该节点的所有子节点
  • ,然后访问每个子节点的所有子节点,依此

类推。这应该可以使用 FIFO 结构轻松实现:

  • 推送根
  • 直到队列为空
  • 获取第一个元素,访问它,然后推送 到队列末尾
  • 其所有子级都重复

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文