python3__leecode/0104.二叉树的最大深度


一、刷题内容

原题链接

https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/

标题内容描述

给定一个二叉树,找出其最大深度。

二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。

说明: 叶子节点是指没有子节点的节点。

示例:
给定二叉树 [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7

返回它的最大深度 3 。

# Definition for a binary tree node.
class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

二、解题方案

1.方法一

深度优先搜索,DFS(Depth First Search)。简单的说就是对每一个可能的分支路径深入到不能深入位置,并且每个节点只能访问一次。先访问root,接着对root的left和right分别递归。

时间复杂度为 O(n),因为每个节点都只访问了一次,最坏空间复杂度O(N)–树完全不平衡,最好空间复杂度O(log n)–树是完全平衡的

class Solution:
    def maxDepth(self, root: TreeNode) -> int:
        if root is None:
            return 0
        else:
            left_tree_depth = self.maxDepth(root.left)
            right_tree_depth = self.maxDepth(root.right)
            return max(left_tree_depth, right_tree_depth) + 1  # 递归深度加+1

2.方法二

使用DFS策略访问每一个节点,并且在循环的时候同时更新深度

时间复杂度为 O(n),空间复杂度O(n)

class Solution:
    def maxDepth(self, root: TreeNode) -> int:
        stack = []  # 一个栈, 用来存储 (当前深度, 当前节点)
        depth = 0

        if root is not None:
            stack.append((1, root))  # 将root节点入栈

        while stack != []:
            cur_depth, node = stack.pop()  # 弹出当前深度和当前节点

            if node is not None:
                depth = max(depth, cur_depth)  # 每次循环的时候都更新下depth
                stack.append((cur_depth + 1, node.left))  # 左节点入栈
                stack.append((cur_depth + 1, node.right))  # 右节点入栈
        return depth

3.方法三

方法一的缩写

class Solution:
    def maxDepth(self, root: TreeNode) -> int:
        return 0 if root is None else max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1

4.方法四

class Solution:
    def maxDepth(self, root: TreeNode) -> int:
        res = []

        def preOrder(p, tmp):
            if p == None:
                res.append(tmp)
                return
            if p != None:
                preOrder(p.left, tmp + 1)
                preOrder(p.right, tmp + 1)

        preOrder(root, 0)
        return max(res)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

百里 Jess

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值