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

文章介绍了如何计算二叉树和N叉树的最大深度,主要方法包括递归遍历和层序遍历。对于二叉树和N叉树,分别给出了递归和迭代的Python实现,最后对解题思路进行了总结。
摘要由CSDN通过智能技术生成

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

三、总结

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

部分内容参考代码随想录

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值