微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

 

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐