类函数返回None

2024-10-04 01:36:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用Python写一个二叉树。我希望我的order遍历返回一个树值数组。它可以很好地打印它们,但是数组从来没有返回到我试图捕获它的变量,并且我的测试失败,没有预期的不相等。你知道吗

def inOrder(self, **kwargs):
        root = self.assignRoot(kwargs)
        arr = self.assignArr(kwargs)
        # recurse down or 'visit' node
        if root.left != None:
            self.inOrder(arr=arr, root=root.left)
        arr.append(root.value)
        if len(arr) == self.length:
            print('returning arr', arr)
            return arr
        if root.right != None:
            self.inOrder(arr=arr, root=root.right)

我的测试是这样的:

from btree import Btree
from btree import Node
def test_inOrder_traversal():
    bst = setUp()
    print(bst.root.value)
    arr = bst.inOrder()
    print('arr', arr)
    expected = [10, 15, 20, 25, 30]
    assert arr == expected

print语句还显示arr==None,因此无法从inoder()正确返回

编辑: 这就解决了。你知道吗

def inOrder(self, **kwargs):
        root = self.assignRoot(kwargs)
        arr = self.assignArr(kwargs)
        # recurse down or 'visit' node
        if root.left != None:
            self.inOrder(arr=arr, root=root.left)
        arr.append(root.value)
        if root.right != None:
            self.inOrder(arr=arr, root=root.right)
        if len(arr) == self.length:
            print('returning arr', arr)
            return arr

Tags: selfrightnoneifvaluedefroot数组