不能遍历二叉树中的任何节点

时间:2012-03-26 14:29:32

标签: python

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

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

viewAll(this)class binTree

中定义

平台:Windows 7 64位中的Python 2.7

#!/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()

2 个答案:

答案 0 :(得分:4)

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

你的问题在这里:

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

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

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

我不确定你打算在这里做什么:

    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()

答案 1 :(得分:0)

请遵守标准,并使用 self 代替

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

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

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