Member Avatar for rbyrd

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)

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

A few test prints might help.

Member Avatar for rbyrd

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 meeting, networking, learning, and sharing knowledge.