【Leetcode笔记】二(N)叉树的最大深度

Leetcode原题链接:
二叉树的最大深度
N 叉树的最大深度

一、思路

  • 仍然是根据遍历解题。
  • 递归三部曲,确定参数和返回值、确定终止条件、确定单层逻辑。本题较为适合后序遍历,分别遍历左右孩子,得到深度后,再比较大小,返回给根节点
  • 一般的迭代遍历不适合解这道题,层序遍历非常合适,之前做过一次,就当再复习一遍了

二、代码

1、递归遍历

(1)二叉树

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def maxDepth(self, root: Optional[TreeNode]) -> int:
        return self.getDepth(root)

    def getDepth(self, node):
        if not node:
            return 0
        l_dep = self.getDepth(node.left)
        r_dep = self.getDepth(node.right)
        depth = 1 + max(l_dep, r_dep)
        return depth

(2)N 叉树

"""
# 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:
        return self.getDepth(root)

    def getDepth(self, node):
        if not node:
            return 0
        curdep = []
        for child in node.children:
            curdep.append(1 + self.getDepth(child))
        if curdep:
            depth = max(curdep)
        else:
            depth = 1
        return depth

2、层序遍历

(1)二叉树

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def maxDepth(self, root: Optional[TreeNode]) -> int:
        if not root:
            return 0
        queue = [root]
        depth = 0
        while queue:
            depth += 1
            for i in range(len(queue)):
                node = queue.pop(0)
                if node.left:
                    queue.append(node.left)
                if node.right:
                    queue.append(node.right)
        return depth

(2)N 叉树

"""
# 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
        queue = [root]
        depth = 0
        while queue:
            depth += 1
            for i in range(len(queue)):
                node = queue.pop(0)
                if node.children:
                    for child in node.children:
                        queue.append(child)
        return depth

三、总结

  • 总结的话都在思路里说了。。

部分内容参考代码随想录

你可能感兴趣的:(leetcode,笔记,算法)