一、刷题内容
原题链接
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)
博客围绕LeetCode上二叉树最大深度问题展开,给出原题链接及描述,即找出给定二叉树的最大深度。同时提供四种解题方案,主要涉及深度优先搜索(DFS),分析了不同方法的时间和空间复杂度。
2106

被折叠的 条评论
为什么被折叠?



