【问题标题】:Implementing Simple Tree in Python在 Python 中实现简单树
【发布时间】:2014-10-26 08:03:17
【问题描述】:

我正在尝试在 Python 中以 OO 方式实现位串 Trie 结构(我只在 Trie 中存储 0 和 1,因此它简化为二叉树的情况)。我似乎在对象传递和引用方面遇到了麻烦。任何帮助将不胜感激。

class Node(object):
    node_count = 0

    def __init__(self, bit):
        Node.node_count += 1
        self.bit = bit
        self.left_child = None
        self.right_child = None

    def add_left_child(self, node):
        self.left_child = node

    def add_right_child(self, node):
        self.right_child = node

    def __str__(self):
        return "(" + str(self.bit) + ")"

def make_trie(strings, trie_root):
    for string in strings:
        current_root = trie_root
        for letter in string:
            if letter == 1 and current_root.right_child is not None:
                current_root = current_root.right_child
            elif letter == 0 and current_root.left_child is not None:
                current_root = current_root.left_child
            else:
                if letter == 1 and current_root.right_child is None:
                    current_root.add_right_child(Node(1))
                    current_root = current_root.right_child
                if letter == 0 and current_root.left_child is None:
                    current_root.add_left_child(Node(0))
                    current_root = current_root.left_child
        current_root.is_string(string)
    return trie_root

root_node = Node(-1)
test_strings = ['1011', '10', '011', '100', '0']
make_trie(test_strings, root_node)

运行后,我得到一个空白节点作为回报。我认为这与我在 make_trie 函数的第 3 行中引用 current_root = trie_root 的方式有关。

任何帮助将不胜感激。

【问题讨论】:

  • strings 实际上是一个字符串列表吗?因为如果是这样:letter == 1letter == 0 将永远不会是 True 并且不会添加任何内容作为子项。
  • 抱歉,这正是问题所在。现在工作正常!
  • 没问题,由于是印刷错误,我将把这个问题标记为关闭。

标签: python oop binary-tree computer-science trie


【解决方案1】:

哇哦。谢谢 IanAuld,我完全傻了。我忘记将字符串转换为整数。 :(

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-22
    • 1970-01-01
    相关资源
    最近更新 更多