Search code examples
pythondata-structuresbinary-search-treeimplementation

BST Insert not working properly in Python


I'm implementing a BST in Python but I have issues with but_insert(t, k). Basically if I just add children to the root, like below, it works:

T = Node(7)
bst_insert(T, 9)
bst_insert(T, 5)

But if I insert another key, then an entire branch from the root seems to be dropped. For instance, if I execute:

T = Node(7)
bst_insert(T, 9)
bst_insert(T, 5)
bst_insert(T, 3)

Then when I print T in order I only get 7 9.

Here is the Node constructor and bst_insert (the print_in_order function works properly so I did not include it).

class Node:
    def __init__(self, key):
        self.key = key
        self.left = None
        self.right = None


def bst_insert(t, k):
    if t is None:
        t = Node(k)

    elif k <= t.key:
        if t.left is None:
            t.left = Node(k)
        else:
            t.left = bst_insert(t.left, k)
    else:
        if t.right is None:
            t.right = Node(k)
        else:
            t.right = bst_insert(t.right, k)

Thanks.


Solution

  •     class Node:
            def __init__(self, key):
                self.key = key
                self.left = None
                self.right = None
    
    
        def bst_insert(t, k):
            if t is None:
                t = Node(k)
    
            elif k <= t.key:
                if t.left is None:
                    t.left = Node(k)
                else:
                    t.left = bst_insert(t.left, k) #1
            else:
                if t.right is None:
                    t.right = Node(k)
                else:
                    t.right = bst_insert(t.right, k) #2
            # return the node, #1 and #2 will always get None value
            return t