Python论坛  - 讨论区

标题:[python-chinese] 从list到tree

2006年07月12日 星期三 20:28

linda.s samrobertsmith at gmail.com
Wed Jul 12 20:28:40 HKT 2006

我加了个list2tree,结果只跑出Capricorn,list2tree什么错吗?
>>> test=['Capricorn', 'Aquarius', 'Cancer', 'Pices']
>>> t=BinaryTree(test[0])
>>> t.list2Tree(test[1:])
>>> t.printTree()
Capricorn

class BinaryTree:

 def __init__(self, key, left=None, right=None, parent=None):
     self.key = key
     self.left = left
     self.right = right
     self.parent = parent

    def list2Tree(self,ls):
        nt=BinaryTree(self.key)
        for node in ls:
            nt.addNode(node)
        return nt

 def addNode(self,key):
     """Add a node in the proper location."""
     if key < self.key:
         if self.left:
             self.left.addNode(key)
         else:
             self.left = BinaryTree(key, parent=self)
     elif key > self.key:
         if self.right:
             self.right.addNode(key)
         else:
             self.right = BinaryTree(key, parent=self)

[导入自Mailman归档:http://www.zeuux.org/pipermail/zeuux-python]

2006年07月12日 星期三 20:55

linda.s samrobertsmith at gmail.com
Wed Jul 12 20:55:54 HKT 2006

糊涂了,我忘记其实新的tree产生了,是w不是t.
>>> w=t.list2Tree(test[1:])
>>> w
<__main__.BinaryTree instance at 0x00BA78F0>
>>> w.printTree()
Capricorn
Aquarius
Cancer
Pices

On 7/12/06, linda. s <samrobertsmith at gmail.com> wrote:
> 我加了个list2tree,结果只跑出Capricorn,list2tree什么错吗?
> >>> test=['Capricorn', 'Aquarius', 'Cancer', 'Pices']
> >>> t=BinaryTree(test[0])
> >>> t.list2Tree(test[1:])
> >>> t.printTree()
> Capricorn
>
> class BinaryTree:
>
>  def __init__(self, key, left=None, right=None, parent=None):
>     self.key = key
>     self.left = left
>     self.right = right
>     self.parent = parent
>
>    def list2Tree(self,ls):
>        nt=BinaryTree(self.key)
>        for node in ls:
>            nt.addNode(node)
>        return nt
>
>  def addNode(self,key):
>     """Add a node in the proper location."""
>     if key < self.key:
>         if self.left:
>             self.left.addNode(key)
>         else:
>             self.left = BinaryTree(key, parent=self)
>     elif key > self.key:
>         if self.right:
>             self.right.addNode(key)
>         else:
>             self.right = BinaryTree(key, parent=self)
>

[导入自Mailman归档:http://www.zeuux.org/pipermail/zeuux-python]

如下红色区域有误,请重新填写。

    你的回复:

    请 登录 后回复。还没有在Zeuux哲思注册吗?现在 注册 !

    Zeuux © 2025

    京ICP备05028076号