简体   繁体   中英

Implementing Simple Tree in Python

I'm trying to implement a bit-string Trie structure in an OO-way in Python (I'm only storing 0's and 1's in the Trie, so it reduces to a case of a Binary Tree). I seem to be having trouble with Object passing & referencing. Any help would be most appreciated.

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)

After running this, I get a blank Node in return. I think it has to do with how I'm referencing current_root = trie_root in line 3 of the make_trie function.

Any help would be much appreciated.

Oh wow. Thanks IanAuld, I was being totally silly. I forgot to cast the strings to ints. :(

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM