无法遍历二进制中的任何节点

2024-05-20 23:29:58 发布

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

当我运行这个程序时,它会打印NameError global name 'viewAll' is not defined

我是个C程序员,我不知道为什么。在

viewAll(this)class binTree中定义

在平台:Python 2.7在windows 7 64位

#!/usr/bin/python
#-*-coding:gbk-*-

class binTree():
    def __init__(this, left = None, right = None, data = 0):
        if data == 0:
            this = None
        else:
            this.leftNode = left
            this.rightNode = right
            this.data = data
    def viewAll(this):
        if this != None:
            print this.data,
            viewAll(this.leftNode)
            viewAll(this.rightNode)

def creatBT():
    temp = input('Please input a number, input "0" for end!')
    if temp == 0:
        return None
    else:
        tree = binTree()
        tree.data = temp
        tree.leftNode = creatBT()
        tree.rightNode = creatBT()
        return tree

if __name__ == "__main__":
    root = creatBT()
    root.viewAll()

Tags: namenonetreeinputdataifdefthis
2条回答

你需要做一个Python教程你不知道实例对象在Python实例方法中是如何工作的。在

你的问题是:

def viewAll(this):
    if this != None:
        print this.data,
        viewAll(this.leftNode)
        viewAll(this.rightNode)

您需要在要调用它的实例上访问viewAll

^{pr2}$

我不知道你打算在这里做什么:

    if data == 0:
        this = None

但实际上您所做的只是将名称this指向该函数调用范围内的None。它不会更改类实例或函数外部的任何内容。在

所以,在viewAll

    if this != None:

将始终是True,因为this又是您在其上调用的viewAll的实例,而且不能设置为None。在


class binTree():
    # I removed __init__ to show you weren't using it
    def viewAll(self):
        print self.data,
        # don't try to show a node that is empty
        if self.leftNode:
            self.leftNode.viewAll()
        if self.rightNode:
            self.rightNode.viewAll()

def creatBT():
    try:
        # don't use input
        temp = int(raw_input('Please input a number, input "0" for end!'))
    except ValueError:
        # in case they don't put in a number
        temp = 0
    if temp == 0:
        return None
    else:
        tree = binTree()
        tree.data = temp
        tree.leftNode = creatBT()
        tree.rightNode = creatBT()
        return tree

if __name__ == "__main__":
    root = creatBT()
    # don't try to show the nodes if none were created
    if root:
        root.viewAll()

请遵守标准并使用self代替this。在

def viewAll(self):
    print self.data,
    self.viewAll(self.leftNode)
    self.viewAll(self.rightNode)

无需测试self(或this)是否为None。在

编辑此解决方案不正确。请看agf的回答。在

相关问题 更多 >