Member Avatar

When using this code to insert 5, then 18, into a binary search tree, the data value 18 is placed as the left child of the root instead of the right child. The statement if data < node.val: (in the insertR method) doesn't seem to be working correctly. Can someone tell me what is wrong? Thanks.

class NODE:
    def __init__(self, data):
        self.val = data
        self.leftChild = None
        self.rightChild = None

class BST:
    def __init__(self):
        self.root = None

    def insert(self,data):  
        if self.root is None:
            self.root = NODE(data)
        else:
            self.insertR(self.root, data)

    def insertR(self, node, data):
        if data < node.val:
            if node.leftChild == None:
                node.leftChild = NODE(data)
            else:
                self.insertR(node.leftChild, data)
        else:
            if node.rightChild == None:
                node.rightChild = NODE(data)
            else:
                self.insertR(node.rightChild, data)

Recommended Answers

Are you sure that you are inserting numbers, not strings?

Jump to Post

All 3 Replies

Are you sure that you are inserting numbers, not strings?

A few test prints might help.

Member Avatar

pyTony: Thanks for your help. I was using strings inadvertently (from repurposed code). It works fine when I use numbers.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.