编程语言
首页 > 编程语言> > Python按层级遍历打印二叉树

Python按层级遍历打印二叉树

作者:互联网

[本文出自天外归云的博客园]

通过列表构造树,按层级遍历打印二叉树:

#!/usr/bin/python
# Write Python 3 code in online editor and run it.
class TreeNode():
    def __init__(self, val):
        self.val = val
        self.left = None
        self.right = None

def list_create_tree(root_node, tree_nodes_val, i):
    if i < len(tree_nodes_val):
        if tree_nodes_val[i] == "#":
            return None
        else:
            root = TreeNode(tree_nodes_val[i])
            root.left = list_create_tree(root.left, tree_nodes_val, 2 * i + 1)
            root.right = list_create_tree(root.right, tree_nodes_val, 2 * i + 2)
            return root
    return root_node

# 按层级打印二叉树
def level_traverse(nodes):
    next_nodes = []
    for node in nodes:
        if node:
            print(node.val)
            next_nodes.append(node.left)
            next_nodes.append(node.right)
    if len(next_nodes) > 0:
        level_traverse(next_nodes)
    
tree_nodes_val = [11,22,33,44,55,66,77,88,99,100,111,"#"]
tree_root_node = list_create_tree(None, tree_nodes_val, 0)
level_traverse([tree_root_node])

 

标签:node,遍历,val,Python,tree,next,二叉树,nodes,root
来源: https://www.cnblogs.com/LanTianYou/p/16361115.html