Chinaunix

标题: binary tree [打印本页]

作者: water0x    时间: 2014-11-06 09:58
标题: binary tree
class BinaryTree:
    def __init__(self, root):
        self.key = root
        self.left = None
        self.right = None

    def tree_walk(self):
        if self.get_root() != None:
            self.left.tree_walk()
            print self.get_root(), " "
            self.left.tree_walk()

    def insert_left(self, new_node):
        if self.left == None:
            self.left = BinaryTree(new_node)
        else:
            t = BinaryTree(new_node)
            t.left = self.left
            self.left = t

    def insert_right(self, new_node):
        if self.right == None:
            self.right = BinaryTree(new_node)
        else:
            t = BinaryTree(new_node)
            t.right = self.right
            self.right = t

    def get_left(self):
        return self.left

    def get_right(self):
        return self.right

    def set_root(self, obj):
        self.key = obj

    def get_root(self):
        return self.key


r = BinaryTree('a')
print "key of root is ", r.get_root()
print "left key of node is ", r.get_left()
r.insert_left('b')
print "now, left key of node is ", r.get_left()
print "what key of left root node is ", r.get_left().get_root()
r.insert_right('c')
print "right key of node is ", r.get_right()
print "what key of right root node is ", r.get_right().get_root()
r.get_right().set_root('hello')
print "has just inserted value is ", r.get_right().get_root()
r.tree_walk()


    self.left.tree_walk()

AttributeError: 'NoneType' object has no attribute 'tree_walk'

这里要怎么改才不是NoneType object遍历
作者: murdercool    时间: 2014-11-06 10:31
猜猜看,是这样?
  1.     def tree_walk(self):
  2.         if self.left != None:
  3.             self.left.tree_walk()
  4.             print self.get_root(), " "
  5.             self.left.tree_walk()
复制代码

作者: water0x    时间: 2014-11-06 19:03
回复 2# murdercool


    def tree_walk(self):
           if self.get_root() != None:
                self.get_left().tree_walk()
                print self.get_root()
                self.get_right().tree_walk()

仍然不对
作者: kyrie_liu    时间: 2014-11-12 17:05
本帖最后由 kyrie_liu 于 2014-11-12 17:25 编辑

def tree_walk(self):
      # 这里其实啥都没啊。
     




欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2