微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

python中的树不打印子元素

如何解决python中的树不打印子元素

我有以下代码,当我运行它时,我无法打印子元素:

class TreeNode:
    def __init__(self,data):
        self.data = data
        self.children = []
        self.parent = None

     #add child node
    def add_child(self,child):
        child.parent = self #the parent of the child is self
        self.children.append(child)

    def print_tree(self):
        print(self.data)
        if self.children:
            for child in self.children:
                child.print_tree()

def build_product_tree():
    root = TreeNode("Fruits") #will be stores in self.data of the treenode
                                  # fruits becomes the parent element

    apple = TreeNode("Apple") #apple becomes the child element Now
    apple.add_child(TreeNode("green apple"))
    apple.add_child(TreeNode("red apple")) #these are children element of the apple node

    mango = TreeNode("Mango") #another child element of fruits
    mango.add_child(TreeNode("ripe mango"))
    mango.add_child(TreeNode("sweet mango"))

    #adding the apple and mango nodes as children to the root of the tree
    root.add_child(TreeNode("Apple"))
    root.add_child(TreeNode("Mango"))

    return root

if __name__ == '__main__':
    root = build_product_tree()
    root.print_tree()
    pass

据我所知,水果是树的根,苹果和芒果是小时候加入的。然而,我希望苹果和芒果的孩子也能被打印出来(青苹果、红苹果等),但他们没有。不太清楚为什么。

解决方法

因为你重新声明了孩子。

root.add_child(TreeNode("Apple"))
root.add_child(TreeNode("Mango"))

你想要:

root.add_child(apple)
root.add_child(mango)

请注意,像 PyCharm 这样的调试器对于识别此类问题非常有用:

enter image description here

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。