• 559. N叉树的最大深度


    给定一个 N 叉树,找到其最大深度。

    最大深度是指从根节点到最远叶子节点的最长路径上的节点总数。

    例如,给定一个 3叉树 :

     

    我们应返回其最大深度,3。

    说明:

    树的深度不会超过 1000。
    树的节点总不会超过 5000。

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/maximum-depth-of-n-ary-tree

    bfs

    """
    # Definition for a Node.
    class Node:
        def __init__(self, val=None, children=None):
            self.val = val
            self.children = children
    """
    
    class Solution:
        def maxDepth(self, root: 'Node') -> int:
            if not root: return 0
            q = [root, None]
            d = 0
            
            while q:
                node = q.pop(0)
                if not node:
                    d += 1
                    if q: q.append(None)
                    continue
                    
                if node and node.children:
                    for child in node.children:
                        q.append(child)
    
            return d
    """
    # Definition for a Node.
    class Node:
        def __init__(self, val=None, children=None):
            self.val = val
            self.children = children
    """
    
    class Solution:
        def maxDepth(self, root: 'Node') -> int:
            if not root:return 0
            if not root.children:return 1
            return max(self.maxDepth(child)+1 for child in root.children)
            
  • 相关阅读:
    电脑分屏鼠标移不到另一个电脑上
    jquery datetimepicker 配置参数
    js获取前n天或者后n天的天数
    mysql查看变量
    Underscore _.template 方法使用详解
    sql优化
    echart图表demo
    jquery预加载的几种例子
    树莓派搭建服务器
    Thymeleaf标签学习
  • 原文地址:https://www.cnblogs.com/xxxsans/p/13795457.html
Copyright © 2020-2023  润新知