leetcode 104. Maximum Depth of Binary Tree 解法 python

一.问题描述

Given a binary tree, find its maximum depth.

The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

Note: A leaf is a node with no children.

Example:

Given binary tree [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

return its depth = 3.

二.解决思路

求二叉树的深度有两种方法,一种是递归一种是非递归。

说实话这道题用递归的方法做非常简单。

我们从下往上数二叉树的深度。

当前节点的深度为左子树和右子树中较大的那个深度再+1.

但是非递归状态就很麻烦,因为我们往深度遍历,就会丢失之前遍历的情况,很难跟踪节点的返回状态(各种非递归的遍历都要要堆栈来保存,但是pop的时候如果需要知道从哪一层pop到哪一层,就得加很多东西,十分复杂)。

所以比较简单的非递归方法就是用广度优先搜索,记录每一层的个数,这一层的遍历完,深度+1,然后继续。

说实话我好久没写二叉树,特别是用python,是真的蒙圈了很久,一开始想着用深度优先搜索非递归,越写与复杂,果断改成广度优先。

当然用递归的话2分钟,1行代码就可以搞定了。

给出两种实现。

之后有高效算法会更新。

更多leetcode算法题解法请关注我的专栏leetcode算法从零到结束或关注我。

欢迎大家一起套路一起刷题一起ac。

三.源码

1.递归

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

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

二.非递归

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

class Solution:
    def maxDepth(self, root: TreeNode) -> int:
        if not root:return 0
        stack=[root]
        depth,cnt_cl=0,1
#cnt_cl record the count of elements in current level
#cnt_nl record the count of elements in next level
        while stack:
            cnt_nl=0
            while cnt_cl:
                curnode=stack.pop(0)
                cnt_cl-=1
                if curnode.left:
                    stack.append(curnode.left)
                    cnt_nl+=1
                if curnode.right:
                    stack.append(curnode.right)
                    cnt_nl+=1
            depth+=1
            cnt_cl=cnt_nl
        return depth

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值