Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/lua/3.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 - Fatal编程技术网

Python 如何按顺序遍历此树并打印出每个元素?

Python 如何按顺序遍历此树并打印出每个元素?,python,Python,我为一个BTree编写了这段代码,但我需要按顺序遍历树,并在遍历树时打印出每个元素。这是BTree的代码。我排除了插入和删除的代码,因为它在这里并不重要 class Node: def __init__(self, leaf=False): self.leaf = leaf self.keys = [] self.child = [] class BTree: def __init__(self, t): self

我为一个BTree编写了这段代码,但我需要按顺序遍历树,并在遍历树时打印出每个元素。这是BTree的代码。我排除了插入和删除的代码,因为它在这里并不重要

class Node:
    def __init__(self, leaf=False):
        self.leaf = leaf
        self.keys = []
        self.child = []

class BTree:
    def __init__(self, t):
        self.root = Node(True)
        self.t = t
    
#code for insert and delete
如果是这样的话,我知道怎么做:

class Node: 
    def __init__(self,key): 
        self.left = None
        self.right = None
        self.val = key 

    def printInorder(root): 
        if root: 
            printInorder(root.left) 
            print(root.val), 
            printInorder(root.right) 

root = Node(1) 
root.left      = Node(2) 
root.right     = Node(3) 
root.left.left  = Node(4) 
root.left.right  = Node(5) 

printInorder(root) 


但我不知道如何将其应用到我的代码中。

您自己做了哪些尝试?你遇到了什么问题?如果
s
代表
self
,请改用
self
——简洁有其局限性,你发现了!我没有真正尝试过任何有意义的东西。不知道从哪里开始。是的,我们代表自己。谢谢你的提示。你知道顺序遍历是什么吗?你知道什么是递归函数吗?通常,你问这类问题的原因是对基本原理缺乏了解,或者不愿意尝试。不要害怕弄错。这是密码。你不是在为核电站编写控制软件。没有东西会爆炸或融化。