繁体   English   中英

二叉搜索树横向

[英]BInary search tree transversals

我对二叉搜索树遍历的递归感到困惑,我迷路了,因为我需要在最后返回一个列表并且不知道如何保存值。它添加了如下所示的值,但我没有获取什么数据类型用于保存这样的值,我也不认为我在正确地穿过树,这是我的代码,不确定我的单元测试是否正确

def inorder(self):

    print("IN INORDER_______________________________")
    print("Printing self.value" + str(self.__value))
    result = []

    if self.__left:
        print("theres self.left")
        print(self.__value)
        #result = result + self.__left 
        #print(result)
        return self.__left.inorder()
        result 
        print(result + "RESULTS")

    if self.__right:

        print("theres self.right")
        print(self.__value)
        return self.__right.inorder()  

    return result



def test_inorder(self):
    bt = family_tree()
    bt.add(15, "jim")
    bt.add(20, "jamie")
    bt.add(25, "fred")
    bt.add(35, "howard")
    bt.add(30, "kc")
    x = bt.inorder()

    expected = '''(15, 'jim'),(20, 'jamie'),(25, 'fred'),(30, 'howard'),(35, 'kc')'''
    self.assertEquals(str(x), expected)
    t = family_tree(bt)
    self.assertEquals(str(t), expected)

您的订单执行中存在问题; 您返回值,而不是将它们连接在一起。

这是基于您的代码的我的实现:

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

    result.append(self.__value)

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

    return result

暂无
暂无

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

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