1、題目描述
https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/
給定一個二叉樹,找出其最大深度。
二叉樹的深度爲根節點到最遠葉子節點的最長路徑上的節點數。
說明: 葉子節點是指沒有子節點的節點。
2、代碼詳解
遞歸寫法(推薦)
# 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
"""
# 遞歸法
if root is None:
return 0
else:
left_height = self.maxDepth(root.left)
right_height = self.maxDepth(root.right)
return max(left_height, right_height) + 1
時間複雜度:我們每個結點只訪問一次,因此時間複雜度爲 O(N), 其中 N 是結點的數量。
空間複雜度:在最糟糕的情況下,樹是完全不平衡的,例如每個結點只剩下左子結點,遞歸將會被調用 N 次(樹的高度),因此保持調用棧的存儲將是 O(N)。但在最好的情況下(樹是完全平衡的),樹的高度將是 log(N)。因此,在這種情況下的空間複雜度將是 O(log(N))。
非遞歸寫法(利用棧)
# 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
"""
# 使用 DFS 策略訪問每個結點,同時在每次訪問時更新最大深度
stack = [] # (depth,node)
if root is not None:
stack.append((1, root))
depth = 0
while stack != []:
current_depth, root = stack.pop()
if root is not None:
depth = max(depth, current_depth)
stack.append((current_depth + 1, root.left))
stack.append((current_depth + 1, root.right))
return depth
時間O(N)、空間O(N)