給定一個二叉樹,找出其最大深度。
二叉樹的深度爲根節點到最遠葉子節點的最長路徑上的節點數。
說明: 葉子節點是指沒有子節點的節點。
示例:
給定二叉樹 [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的運行時間消耗更長,內存消耗是一樣的。