使用类打印二叉树

时间:2014-12-14 17:49:35

标签: python class

我创建了2个用于创建二叉树和使用递归添加节点的函数:

创建根目录:

def create_node(number = None):
    return {"number": number, "right": None, "left":None}

使用递归添加节点:

def insert(number, pointer):
    pointer_number=pointer["number"]
    if pointer_number is None:
        pointer["number"]=number
    elif number > pointer_number:
        if pointer["right"] is None:
            pointer["right"] = create_node(number) 
        else:
            insert(number, pointer["right"])
    else:
        if pointer["left"] is None:
            pointer["left"] = create_node(number)
        else:
            insert (number, pointer["left"])

最近我开始上课,我仍然试图抓住这个。我想做的是通过使用一个名为Node的类来创建相同的逻辑:

class Node(object):
    def __init__(self, number):
        self.number=number
        self.right=None
        self.lef=None

    def add_node(self,number):
        if number < self.number:
            if self.left is None:
                self.left = __init__(number)
            else:
                self.left = self.left.add_node(number)
        if number > self.number:
            if self.right is None:
                self.right = __init__(number)
            else:
                self.right = self.right.add_node(number)

    def see_tree(self):
        print(self.number)

我面临的问题是add_node函数。当我试图运行它时,我收到此错误:

  

&#39;节点&#39;对象没有属性&#39; left&#39;

有关如何使这项工作的任何想法?欣赏它!

1 个答案:

答案 0 :(得分:0)

代码中的拼写错误:self.lef = None中的__init__。我认为你的意思是self.left = None