mathfreshman
mathfreshman

Reputation: 1

Python: actually modify a node in binary search tree instead of just attaching a label name

I understand how to insert using recursion. I also understand why this code doesn't work as expected because while I'm updating the variable "current" in the "insert" method, I'm only attaching the name label "current" to some node, copy that node to "current" and modify "current", but not the actual node in the binary search tree.

So how can I actually modify the node in the binary search tree using the iterative concept here? And more generally speaking, how can I make a "shallow copy" to any object I created and actually modify that object? A "list" object in Python is an example that has the desired property. What code in "list" makes it behave this way? Thanks in advance.

class Node:

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

class BinarySearchTree:

    def __init__(self, root=None):
        self.root = root

    def insert(self, data):
        if self.root:
            current = self.root
            while current:
                if data < current.data:
                    current = current.left
                elif data > current.data:
                    current = current.right
            current = Node(data)
        else:
            self.root = Node(data)

bst = BinarySearchTree()
bst.insert(2)
bst.insert(1)
bst.insert(3)

Upvotes: 0

Views: 715

Answers (1)

Narendra Vidda hub
Narendra Vidda hub

Reputation: 1

I think you are looking for something like below code snippets.

Please let me know if you need some clarification.

class Node:

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

class BinarySearchTree:

    def __init__(self, root=None):
        self.root = Node(root) if root else None

    def insert(self, data):
        if data < self.data:
            if not self.left:
                self.left = Node(data=data)
            else:
                BinarySearchTree.insert(self=self.left, data=data)
            return True
        elif data > self.data:
            if not self.right:
                self.right = Node(data=data)
            else:
                BinarySearchTree.insert(self=self.right, data=data)
            return True
        else:
            print(f"Node with data {data} already inserted")

bst = BinarySearchTree(root=15)
BinarySearchTree.insert(self=bst.root, data=2)
BinarySearchTree.insert(self=bst.root, data=1)
BinarySearchTree.insert(self=bst.root, data=3)

print("root : ", bst.root.data)
print("root left : ", bst.root.left.data)
print("root left left : ", bst.root.left.left.data)
print("root left right: ", bst.root.left.right.data)

Upvotes: 0

Related Questions