Python教程

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])

 

这篇关于Python按层级遍历打印二叉树的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!