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

Original: https://www.cnblogs.com/LanTianYou/p/16361115.html
Author: 天外归云
Title: Python按层级遍历打印二叉树

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/15743/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

发表回复

登录后才能评论
免费咨询
免费咨询
扫码关注
扫码关注
联系站长

站长Johngo!

大数据和算法重度研究者!

持续产出大数据、算法、LeetCode干货,以及业界好资源!

2022012703491714

微信来撩,免费咨询:xiaozhu_tec

分享本页
返回顶部