简体   繁体   中英

Assign a object to the pointer the node is referring

class BinarySearchTree:

    def __init__(self, value=None, left=None, right=None):
        self.value = value
        self.left = left
        self.right = right

    def insert(self, value) -> bool:
        current_node = self

        while current_node is not None:
            if current_node.value < value:
                current_node = current_node.left
            elif current_node.value == value:
                return False
            elif current_node.value > value:
                current_node = current_node.right

        # id(current_node) <-- I need to create a object on this
        current_node = BinarySearchTree(value)  # <--
        # id(current_node) <-- This is a new assigned id, but I need the same as the previous id

        return True

binary_search_tree = BinarySearchTree(2)
binary_search_tree.insert(5)

print(binary_search_tree.__dict__)

current_node refers to current_node.left or current_node.right .

I need to create a new object and assign it to the pointer the current_node is referring,

but I only create a new object and assign it to a new pointer.

a new assigned id, but I need the same as the previous id

After the loop, as Scott Hunter noted, current_node is None , so the previous id is the “identity” of None , and you surely understand that a new object 's id cannot be the same as the id of None . What you could do is modify the loop in a way which allows to refer to the attribute left or right afterwards as needed:

        while current_node is not None:
            object = current_node   # remember the node to be changed
            if current_node.value < value:
                current_node = current_node.right
                name = 'right'      # remember the attribute to be changed
            elif current_node.value == value:
                return False
            elif current_node.value > value:
                current_node = current_node.left
                name = 'left'       # remember the attribute to be changed
        setattr(object, name, BinarySearchTree(value))  # make the change

Alternatively you could make things a bit more simple by replacing in __init__

        self.left = left
        self.right = right

with

        self.subtree = [left, right]

and the whole body of insert with

        if value == self.value: return False
        t = 0 if value < self.value else 1
        if self.subtree[t]: return self.subtree[t].insert(value)
        self.subtree[t] = BinarySearchTree(value)
        return True

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-2025 STACKOOM.COM