104.二叉树的最大深度
题目:
给定一个二叉树 root
,返回其最大深度。
二叉树的 最大深度 是指从根节点到最远叶子节点的最长路径上的节点数。
示例 1:
输入:root = [3,9,20,null,null,15,7] 输出:3
示例 2:
输入:root = [1,null,2] 输出:2
提示:
- 树中节点的数量在
[0, 104]
区间内。 -100 <= Node.val <= 100
解题思路:
使用深度优先搜索的思想,用栈存储当前的节点地址和节点的深度,如果遍历到树叶节点就将栈顶元素输出,height返回到上一节点的深度
使用广度优先搜索的思想,用队列存储每一层节点
DFS代码:
# 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) -> int:
if not root:
return 0
stack = []
height = 0
current = root
max_height = 0
while current or stack:
while current:
height+=1
stack.append((current, height))
current = current.left
max_height = max(height, max_height)
current = stack[-1][0]
height = stack[-1][1]
stack.pop()
current = current.right
return max_height
这里可以使用递归的思想来做深度优先搜索
递归DFS代码:
class Solution:
def maxDepth(self, root) -> int:
if not root:
return 0
else:
left_height = self.maxDepth(root.left)
right_height = self.maxDepth(root.right)
return max(left_height, right_height)+1
BFS代码:
import queue
class Solution:
def maxDepth(self, root) -> int:
if not root:
return 0
tree_queue = queue.Queue()
height = 0
tree_queue.put(root)
while not tree_queue.empty():
length = tree_queue.qsize()
while length>0:
current = tree_queue.get()
if current.left:
tree_queue.put(current.left)
if current.right:
tree_queue.put(current.right)
length-=1
height+=1
return height