简体   繁体   English

Python中的二叉树有序遍历

[英]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: 上面的语句创建一个包含None项目的列表:

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. 您的代码在遍历一个子树后跳过其他子树根目录而返回。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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