给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。
示例:
给定二叉树 [3,9,20,null,null,15,7]
3
/ \
9 20
/ \
15 7
返回它的最大深度 3 。
解法一(递归法):
首先我说一些我对于树这系列的算法题的理解(可能有些肤浅,如有不对,还望指正),树这系列我认为都可以使用递归的方法就解决,因为实际上每个树节点的结构都是一模一样的。当我们能够用一个函数处理一个树节点(结构有左子结点,根节点,右节点)时,实际上我们使用递归的方法,让这个函数接着去处理拥有同样树结构的左右子节点。
具体实现代码如下:
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def maxDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
num = 0
if not root is None:
return 1 +max(self.maxDepth(root.left), self.maxDepth(root.right)) # 进行递归
else:
return 0 # 如果节点为空,则结束递归
解法二(迭代):
BFS(Breadth-first search)和DFS(Depth-first search)两种搜索树节点的方法。
遍历方法可以是前序遍历,后序遍历,中序遍历。
思路:当我们去思考使用迭代来遍历节点的时候,我们肯定需要使用数据结构(栈、队列)来辅助我们去遍历根节点。使用栈的话,根据栈的“先进后出”,应当是DFS(深度优先搜索),根据队列的“先进先出”,应当是BFS(广度优先搜索)
BFS,要用到队列,所以是cur_dep, node = ans.pop(0)
class Solution:
def maxDepth(self, root: TreeNode) -> int:
# BFS
if root is None:
return 0
queue = []
queue.append((1,root))
depth = 0
while queue:
cur_dep, node = queue.pop(0)
depth = max(depth, cur_dep)
if node.left is not None:
queue.append((cur_dep+1,node.left))
ans.append((cur_depth+1,node.right)) if node.right else 0 # python中if的简洁写法
return depth
DFS与BFS有两点不同:
1. 要用到栈而不是队列,所以是cur_dep, node = stack.pop()
class Solution:
def maxDepth(self, root: TreeNode) -> int:
# DFS
if root is None:
return 0
stack = []
stack.append((1,root))
depth = 0
while stack:
cur_dep, node = stack.pop()
depth = max(depth, cur_dep)
if node.right is not None:
stack.append((cur_dep+1,node.right))
if node.left is not None:
stack.append((cur_dep+1,node.left))
return depth
从最终结果来看BFS的运行时间更短,DFS的运行时间消耗更长,内存消耗是一样的。