【发布时间】: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 == 1或letter == 0将永远不会是True并且不会添加任何内容作为子项。 -
抱歉,这正是问题所在。现在工作正常!
-
没问题,由于是印刷错误,我将把这个问题标记为关闭。
标签: python oop binary-tree computer-science trie