简体   繁体   中英

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)

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM