【力扣日记】559 N叉树的最大深度 | DFS

这里先复习一遍二叉树的最大深度

class Solution:
	def DEEPEST(self,root):
		if not root:return 0
		return max(self.DEEPEST(root.left),self.DEEPEST(root.right))+1

题目描述

给定一个 N 叉树,找到其最大深度。
最大深度是指从根节点到最远叶子节点的最长路径上的节点总数。

"""
# Definition for a Node.
class Node:
    def __init__(self, val=None, children=None):
        self.val = val
        self.children = children
        children是列表类型,元素是树节点。
"""

算法

采用DFS:深度优先搜索。

第一版:粗糙

class Solution:
    def maxDepth(self, root: 'Node') -> int:
        def DFS(root):
            ls=[]
            if not root:return 0
            if not root.children:return 1
            for i in root.children:
                print(i.val)
                ls.append(DFS(i))
            print(ls)
            k=max(ls)+1
            return k
        k=DFS(root)
        return k

IMPROVE

class Solution:
    def maxDepth(self, root: 'Node') -> int:
        if not root:return 0
        if not root.children:return 1
        return max([self.maxDepth(i)for i in root.children])+1

执行用时 :48 ms, 在所有 Python3 提交中击败了82.28%的用户
内存消耗 :15.6 MB, 在所有 Python3 提交中击败了7.01%的用户

发布了210 篇原创文章 · 获赞 20 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/Heart_for_Ling/article/details/104781665