﻿ Python 二叉树 层遍历&输出层数 - 军军小站|张军博客

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

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

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.preOrderTrave(btree.root)
print("\n")
btree.levelTrave(btree.root)

QQ号联系： 360901061

【本文对您有帮助就好】