2

我上面有一个简单的程序,它从排序数组创建一个 BST。它应该解析树而不显示本质上为无的叶子。有人可以帮助解释为什么程序仍然吐出“无”。我是 python NooB 并且希望得到任何帮助。我已经尝试过 != 'None' 以及 is None 但得到相同的结果。

class Node:
    def __init__(self,value):
        self.value=value
        self.nodeleft=None
        self.noderight=None

def makeBST(ia,start,end,tree):
    if (end < start):
        return None
    mid = (start + end) / 2
    n = Node(ia[mid])
    n.nodeleft = makeBST(ia, start, mid-1, tree)
    n.noderight = makeBST(ia, mid+1, end, tree)
    tree.append(n)
    return n

def printBST(root):
    print 'RR' ,root.value
    if root.nodeleft == None:
        print 'EOT'
    else:    
        print printBST(root.nodeleft)

    if root.noderight == None:
        print 'EOT'
    else:    
        print printBST(root.noderight)

if __name__ == '__main__':
    array = [1, 2, 3, 4, 5, 6]
    dic = []
    root = makeBST(array, 0, len(array)-1, dic)
    printBST(root)
4

2 回答 2

4

The problem is that your code was passing the return value of printBST to print. Since printBST does not return anything, None was printed.

So when you wrote:

print printBST(root.nodeleft)

that code is certain to print None because printBST does not contain a return statement and so defaults to returning None.

You need to change printBST to do this:

def printBST(root):
    print 'RR' ,root.value
    if root.nodeleft is None:
        print 'EOT'
    else:    
        printBST(root.nodeleft)

    if root.noderight is None:
        print 'EOT'
    else:    
        printBST(root.noderight)

Note also that using is is the correct way to test for None.

That said, you can make your code simpler like this:

def printBST(root):
    if root is None:
        print 'EOT'
        return
    print 'RR', root.value
    printBST(root.nodeleft)
    printBST(root.noderight)

As well as being simpler, this code has the additional benefit of not failing when presented with an empty tree.

于 2013-10-06T13:34:21.530 回答
2

printBST应该return值,而不是print它们。因为它不返回任何东西,所以它默认为None. 这就是为什么printBST(root) is None

printBST(root)其本身不会自行打印该值。你必须在print前面加上:

print printBST(root)

根据PEP 8,您永远不应该将 NoneType 单例与相等运算符(例如==and !=)进行比较。使用is None和/或is not None

于 2013-10-06T13:30:45.767 回答