【问题标题】:Attribute binary code as the path from binary tree in Python属性二进制代码作为Python中二叉树的路径
【发布时间】:2013-04-28 20:43:37
【问题描述】:

如何根据符号在二叉树中的路径将二进制代码归因于符号?换句话说,一本字典。

一棵树的例子:

tree=[['a', 'p'], [[['n', 'u'], 'o'], ' ']]

或者如果您愿意:

tree=[
        ['a', 'p'],
        [
            [
                ['n', 'u'],
                'o'
            ],
            ' '
        ]
     ]

我尝试使用递归方法到达指定符号,并将其路径记录为字符串,添加 0 或 1,因为它遍历分支,但没有成功,我不知道如何从根开始遍历树。

谁能告诉我最好的方法?

【问题讨论】:

    标签: python binary-tree huffman-code


    【解决方案1】:

    继续你之前的问题,如果你需要输入一长串字符并且你不知道每个字符何时被切断:

    global tree #just declare the tree globally -- this is just shorthand
    def findMessage(t, s):
        if (s == ""):
            return ""
        if(isinstance(t, str)):
            return t + findMessage(tree[int(s[0])], s[1:])
        return findMessage(t[int(s[0])], s[1:])
    

    s 是您尝试读取的字符串,t 是您要探索的树的部分。

    【讨论】:

    • 什么是't'和's'?我假设's'是符号,我不确定't'。谢谢你的回答。
    • 抱歉 -- s 是您要读取的字符串,t 是您要探索的树的部分。
    • 但是你需要一个 pop() 来删除我们刚刚找到的元素,所以我们定义了要探索的内容,对吧?当您使用您建议的方法时,您得到的输出是什么?
    • 我认为你不会删除它——你只是复制它?
    • 'an opaa pppn po' from '00100011101010000110101011000110110100' 这个方法假设每个字母不是四位
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-07
    • 1970-01-01
    • 1970-01-01
    • 2021-05-16
    相关资源
    最近更新 更多