遍历哈夫曼树

发布于 2024-12-09 12:17:04 字数 339 浏览 1 评论 0原文

所以目前我有一个创建霍夫曼树的程序。树由具有以下字段的“Hnode”组成: 右(指向右子节点) 左(指向左子节点) 代码(整数字符串,理想情况下 0 和 1 将成为该节点的霍夫曼代码) 字符(节点中包含的字符)。

我通过从链表添加节点来创建哈夫曼树 - 我知道树已正确创建。当我创建树时,当我给它一个父节点时,我告诉节点,如果它是父节点的“右”,则其代码字符串为1,如果左为0。但是显然在创建整个树之后,每个节点都是只会有 0 或 1,但还没有像 00100101 这样的字符串。我的问题是,既然我有了这棵树,我可以遍历它吗?我理解这个想法是给每个孩子其父母的代码+孩子自己的代码,但我不明白如何循环遍历树来完成此任务。

先感谢您。

So Currently I have a program that creates a huffman tree. the tree is made up of "Hnodes" with these fields: right (points to right child) left (points to left child) code (string of integers, ideally the 0's and 1's that will be the huffman code of this node) character (the character contained in the node).

I have created the huffman tree by adding nodes from a linked list - i know the tree was created correctly. As i created the tree, i told the node when i gave it a parent node, that if it was the parent's "right", its code string was 1, if left 0. However obviously after the entire tree is created, each node is only going to have either a 0 or 1, but not yet a string like 00100101. My question is, now that I have this tree, can can I traverse it? I understand the thought would be to give each child its parent's code + the child's own code, but I do not understand how to loop through the tree to accomplish this.

Thank you in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

情徒 2024-12-16 12:17:04

也许是这个?

  ExpandBinaryPaths(node, prefix)
  1. if node is null then return 
  2. else then
  3.    node.binary = prefix concat node.binary
  4.    ExpandBinaryPaths(node.left, node.binary)
  5.    ExpandBinaryPaths(node.right, node.binary)
  6.    return

这个想法是你可以在没有前缀的根上调用它... ExpandBinaryPaths(root, "")。

Maybe this?

  ExpandBinaryPaths(node, prefix)
  1. if node is null then return 
  2. else then
  3.    node.binary = prefix concat node.binary
  4.    ExpandBinaryPaths(node.left, node.binary)
  5.    ExpandBinaryPaths(node.right, node.binary)
  6.    return

The idea is you would call this on the root with no prefix... ExpandBinaryPaths(root, "").

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