Search code examples
pythondata-structuresbinary-search-treetypeerror

Type error when trying to build binary search tree in python


I am trying to build a BST but when I try to run the program I get the following error:

TypeError: 'method' object is not iterable

I am not sure why this is happening since I would assume the in_order_traversal method would be an attribute of the BST class. Below is my code.

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

    def add_child(self,data):
        if data == self.data: #check if value already exists in tree
            return

        if data <self.data: #should go on the left side then

            if self.left: #check if left tree has a value
                self.left.add_child(data) #if it has a value, use add_child method to add another child to the left
            else: #if it does not have a value
                self.left = BST(data)


        else:
            if self.right:
                self.right.add_child()
            else:
                self.right = BST(data) #if there is no right tree, init a new right tree with data

    #visit left, root then right
    def in_order_traversal(self):
        elements = []

        if self.left:
            elements += self.left.in_order_traversal()

        elements.append(self.data) #append the root

        if self.right:
            elements += self.right.in_order_traversal


        return elements



def build_tree(data):
    root = BST(data[0])

    for i in range(1,len(data)):
        root.add_child(data[i])
    return root

if __name__ == '__main__':
    numbers = [12,3,1,20]
    numbers_tree = build_tree(numbers)
    print(numbers_tree.in_order_traversal())

Solution

  • def in_order_traversal(self):
        elements = []
    
        if self.left:
            elements += self.left.in_order_traversal()
    
        elements.append(self.data) 
    
        if self.right:
            elements += self.right.in_order_traversal()        #CHANGE
    
        return elements
    

    You actually forgot to write parenthesis after in_order_traversal method, which caused the error.