zoukankan      html  css  js  c++  java
  • LeetCode559. Maximum Depth of N-ary Tree

    第一次写出了具有迭代和递归的函数,还是有点收获的,虽然题目比较简答

    当要对某些对象重复使用时,考虑循环,也就是迭代

    当函数可以简化一个重复的操作时,考虑递归,而且就当下一次使用这和函数的结果已经有啦,就不会考虑的太复杂

    自己写的答案:

    """
    # Definition for a Node.
    class Node(object):
        def __init__(self, val, children):
            self.val = val
            self.children = children
    """
    class Solution(object):
        def maxDepth(self, root):
            """
            :type root: Node
            :rtype: int
            """
            if not root:
                return 0
            if not root.children:
                return 1
            sub_max=[]
            for child in root.children:
                sub_max.append(self.maxDepth(child)+1) 
            return max(sub_max)

    反思学习:

       1.对list不知道是None还是[ ]的时候,使用 if not list

       2.list 添加元素使用append

      3.list取最值max

    优秀答案:

    class Solution(object):
        def maxDepth(self, root):
            """
            :type root: Node
            :rtype: int
            """
            if not root:
                return 0
            if not root.children:
                return 1
            depth = 1 + max(self.maxDepth(child) for child in root.children)
            return depth

    没有使用list,很简洁

    """
    # Definition for a Node.
    class Node(object):
        def __init__(self, val, children):
            self.val = val
            self.children = children
    """
    class Solution(object):
        def maxDepth(self, root):
            """
            :type root: Node
            :rtype: int
            """
            if not root: return 0
            depth = 0
            que = collections.deque()
            que.append(root)
            while que:
                size = len(que)
                for i in range(size):
                    node = que.popleft()
                    for child in node.children:
                        que.append(child)
                depth += 1
            return depth

    使用了队列,层序遍历记录层数

  • 相关阅读:
    [LeetCode] 582. Kill Process
    [LeetCode] 686. Repeated String Match
    [LeetCode] 341. Flatten Nested List Iterator
    [LeetCode] 404. Sum of Left Leaves
    [LeetCode] 366. Find Leaves of Binary Tree
    [LeetCode] 1485. Clone Binary Tree With Random Pointer
    [LeetCode] 459. Repeated Substring Pattern
    [LeetCode] 565. Array Nesting
    [LeetCode] 679. 24 Game
    [LeetCode] 364. Nested List Weight Sum II
  • 原文地址:https://www.cnblogs.com/captain-dl/p/10140284.html
Copyright © 2011-2022 走看看