Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/343.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python中的树不打印子元素_Python_Algorithm_Data Structures_Tree - Fatal编程技术网

python中的树不打印子元素

python中的树不打印子元素,python,algorithm,data-structures,tree,Python,Algorithm,Data Structures,Tree,我有以下代码,运行时无法打印子元素: 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 i

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

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)
注意:类似调试器的调试器对于识别以下问题非常有用:


因为你重新申报了孩子们

root.add_child(TreeNode("Apple"))
root.add_child(TreeNode("Mango"))
你想要:

root.add_child(apple)
root.add_child(mango)
注意:类似调试器的调试器对于识别以下问题非常有用: