K..
K..

Reputation: 93

Binary tree inorder traversal in Python

I don't think I'm traversing it correctly and its returning empty when it needs to return a new list. I've been stuck for a while and still need to do all the other traversals. Will provide unit test for needed output but my unit test might be wrong.

def inorder(self):

    print("in INOrDER is entered")
    temp = [None]


    if self.__left:
        temp = temp.append(self.__left)
        return self.__left.inorder() 
    elif self.__right: 
        temp = temp.append(self.__right)
        return self.__right.inorder() 
    return temp


def test_inorder(self):
    bt = family_tree()
    bt.add(20, "melanie")
    bt.add(10, "edwin")
    bt.add(30, "junior")
    bt.add(25, "dora")
    bt.add(35, "kate")
    x = bt.inorder()

    expected = '''(10, 'edwin'),(20, 'melanie'),(25, 'dora'),(30, 'junior'),(35, 'kate')'''
    self.assertEquals(str(x), expected)
    t = family_tree(bt)
    self.assertEquals(str(t), expected)

Upvotes: 2

Views: 852

Answers (2)

Old Fox
Old Fox

Reputation: 8725

There are 2 problems in your implementation:

temp = [None]

The above statement creates a list with a None item:

x = len(temp) # x value will be 1

The second problem is your method appending logic; you return the values instead of append them.

Here is an implementation base on your code:

def inorder(self):
    result = []
    if self.__left:
        result += self.__left.inorder()

    result.append(self.__value)

    if self.__right:
        result += self.__right.inorder()

    return result

Upvotes: 6

Scott Hunter
Scott Hunter

Reputation: 49803

An in-order traversal would need to descend into both sub-trees if present, and visit the root in between; your code returns after traversing a sub-tree, skipping over the other sub-tree and the root.

Upvotes: 0

Related Questions