Python 二叉树 层遍历&输出层数

系统 573 0
            
              class BTNode(object):
    def __init__(self, key=None, lchild=None, rchild=None):
        self.key = key
        self.lchild = lchild
        self.rchild = rchild

class BiTree(object):
    def __init__(self, data_list):
        self.root = BTNode()
        self.queue = []  # 用于存放正在操作的子树的三个节点,依次是root, left, right
        
    def add(self, ele):
        new_node = BTNode(ele)
        self.queue.append(new_node)
        if self.root.key is None:
            self.root = new_node
        else:
            tree_node = self.queue[0]
            if tree_node.lchild is None:
                tree_node.lchild = new_node
            else:
                tree_node.rchild = new_node
                self.queue.pop(0)

    
    def preOrderTrave(self, bt):
        if bt is not None:
            print(bt.key, end=" ")
            self.preOrderTrave(bt.lchild)
            self.preOrderTrave(bt.rchild)
            
    def levelTrave(self, bt):
        if bt is not None:
            queue =[bt]
            level = 0
            while queue:
                print(level, "层:", end=":")
                for i in range(len(queue)):
                    bt = queue.pop(0)
                    print(bt.key, end=" ")
                    if bt.lchild != None:
                        queue.append(bt.lchild)
                    if bt.rchild != None:
                        queue.append(bt.rchild)
                level = level + 1
                print("\n")

btree = BiTree(data_list)
for i in range(20):
    btree.add(i)
        
btree.preOrderTrave(btree.root)
print("\n")
btree.levelTrave(btree.root)
            
          

 


更多文章、技术交流、商务合作、联系博主

微信扫码或搜索:z360901061

微信扫一扫加我为好友

QQ号联系: 360901061

您的支持是博主写作最大的动力,如果您喜欢我的文章,感觉我的文章对您有帮助,请请扫描上面二维码支持博主1元、2元、5元等您想捐的金额吧,狠狠点击下面给点支持吧

发表我的评论
最新评论 总共0条评论