使用Preorder Traversal构造二叉树并将值存储在列表中

时间:2016-01-14 04:47:03

标签: python list global

当我尝试将值附加到全局列表时,它会显示错误。

list1 = []

class Node:

    def __init__(self,data):

            self.data = data
            self.left = None
            self.right = None
            self.root = None

        def getData(self):
            return self.data

        def setData(self,data):
            self.data = data

        def insertleft(self,data):
            if self.left == None:
                self.left = Node(data)
                return
            else:
                self.left.setData(data)
                return

        def insertright(self,data):
            if self.right == None:
                self.right = Node(data)
                return
            else:
                self.right.setData(data)
                return

        def insert(self,data):
            if self.data == data:
                return -1
            elif self.data > data:
                self.insertleft(data)
            else:
                self.insertright(data)


        def preorder(self,list1):
            if self.root:
                global list1.append(self.root)
                preorder(self.left,global list1)
                preorder(self.right,global list1)
                return list1



a = Node(99)    
a.insert(10)    
a.insert(101)   
a.insert(108)   
a.insert(9)

print a.preorder(global list1)

0 个答案:

没有答案