我试图在Python中以OO方式实现位字符串Trie结构(我只在Trie中存储0&1;和1' s,因此它减少了对于二叉树的情况)。我似乎遇到了对象传递和问题的困难。引用。任何帮助都将非常感激。
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)
运行之后,我得到一个空白节点作为回报。我认为这与我在current_root = trie_root
函数的第3行中引用make_trie
的方式有关。
非常感谢任何帮助。
答案 0 :(得分:0)