编程语言
首页 > 编程语言> > 求二叉树每层节点最大值,python实现

求二叉树每层节点最大值,python实现

作者:互联网

# 求二叉树每层的最大值
def greatest_nodes(root):
    if not root:
        return None

    next_layer = [root]
    res = []
    while next_layer:
        temp_next_layer = []
        layer_value = []
        for node in next_layer:
            if not node:
                continue
            layer_value.append(node.val)
            if node.left:
                temp_next_layer.append(node.left)
            if node.right:
                temp_next_layer.append(node.right)

        next_layer = temp_next_layer
        res.append(max(layer_value))
    return res

标签:node,layer,temp,python,res,每层,next,二叉树,append
来源: https://blog.csdn.net/qq_33356414/article/details/91398526