一.问题描述
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