【问题标题】:BInary search tree transversals二叉搜索树横向
【发布时间】:2016-05-07 10:09:44
【问题描述】:

我对二叉搜索树横向的递归感到困惑,我只是迷路了,因为我需要在最后返回一个列表并且不知道如何保存值。它添加了如下所示的值,我不知道使用什么数据类型来保存这样的值我也不认为我在树中正确移动这是我的代码,不确定我的单元测试是否正确

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)

【问题讨论】:

  • 我猜你的inorder 方法有一些错误。位于 return 语句之后的代码(例如在像你的 if self.__right 这样的分支中)永远不会执行。排除 print 语句,您的函数可能会简化为 def inorder(self): if self.__left: return self.__left.inorder() elif self.__right: return self.__right.inorder() else: return [] 之类的东西,这不是一个精确的答案,但您可以使用对象的其他属性(比如说self.result)来添加您需要在每次递归中存储的值,直到您重新完成并返回它。

标签: python unit-testing data-structures binary-tree binary-search-tree


【解决方案1】:

你的顺序执行有问题;您返回值而不是将它们连接在一起。

这是我根据您的代码实现的:

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

    result.append(self.__value)

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

    return result

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-08
    • 1970-01-01
    • 2010-10-26
    • 1970-01-01
    相关资源
    最近更新 更多