Python二进制树

时间:2013-10-15 09:44:28

标签: python-3.x binary-tree

我正在使用Python3中的二叉树,到目前为止,几乎所有内容都按预期工作;但是,我有一个函数应该返回任何给定节点的所有子节点的列表,无论出于什么原因我只获取对象地址列表,而不是调用我重写的__str__(self)方法。

from collections import deque  # http://docs.python.org/3.1/tutorial/datastructures.html

class BinaryNode:  # binary tree functionality via iterative means

    def __init__(self, name, data):
        self.Left = None
        self.Right = None
        self.Parent = None
        self.Name = name
        self.Data = data
        return

    def AddNew(self, name, data):
        q = []
        q.append(self)
        while q:
            i = q.pop()
            if i.Name == name:
                i.Data = data
                return i
            elif name < i.Name:
                if i.Left:
                    q.append(i.Left)
                else:
                    i.Left = BinaryNode(name, data)
                    i.Left.Parent = i
                    return i.Left
            else:
                if i.Right:
                    q.append(i.Right)
                else:
                    i.Right = BinaryNode(name, data)
                    i.Right.Parent = i
                    return i.Right

    def Find(self, name):
        q = deque()
        q.append(self)
        '''if self.Left: q.append(self.Left)
        if self.Right: q.append(self.Right)'''
        while q:
            i = q.pop()
            print(i)
            if i.Name == name:
                return i
            elif name < i.Name:
                if i.Left: q.append(i.Left)
                else: return None
            else:
                if i.Right: q.append(i.Left)
                else: return None

    def Children(self):
        children = []
        q = deque()
        if self.Left: q.append(self.Left)
        if self.Right: q.append(self.Right)
        while q:
            i = q.popleft()
            if i.Left: q.append(i.Left)
            if i.Right: q.append(i.Right)
            children.append(i)
        return children

    def Parents(self):
        lst = []
        i = self.Parent
        while i is not None:
            lst.append(i)
            i = i.Parent
        return lst

    def __str__(self): return "{} : {}".format(self.Name, self.Data)

我正在通过调用

进行测试
test = BinaryNode("Jesse", 21)
print(test)
print(test.AddNew("David", 22))
print(test.AddNew("Marli", 23))
print(str(test.Children()))
print(test.Find("David"))
print(test.Find("David").Children())
print(test.Find("Gary")) #Will return None

使用生成的控制台输出

Jesse : 21
David : 22
Marli : 23
[<__main__.BinaryNode object at 0x000000000333E160>, <__main__.BinaryNode object at 0x000000000333E1D0>, <__main__.BinaryNode object at 0x000000000333E198>]
David : 22
[<__main__.BinaryNode object at 0x000000000333E1D0>]
None

更新 以下是我实施的答案:

def __repr__ (self): return str(self)

1 个答案:

答案 0 :(得分:3)

Python容器始终使用包含对象的表示

也实施__repr__方法,并在打印列表时使用;如果您愿意,可以将其设为__str__的别名:

 __repr__ = __str__

或明确打印列表中的每个元素:

print(', '.join(map(str, test.Children())))