給定一個二叉樹,找出其最大深度。python
二叉樹的深度爲根節點到最遠葉子節點的最長路徑上的節點數。app
說明: 葉子節點是指沒有子節點的節點。code
示例:
給定二叉樹 [3,9,20,null,null,15,7]
,遞歸
3 / \ 9 20 / \ 15 7
返回它的最大深度 3 。io
利用遞歸的深度優先搜索class
複雜度分析二叉樹
show me the code搜索
class Solution: 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
咱們還能夠在棧的幫助下將上面的遞歸轉換爲迭代。方法
咱們的想法是使用 DFS 策略訪問每一個結點,同時在每次訪問時更新最大深度。時間
因此咱們從包含根結點且相應深度爲 1
的棧開始。而後咱們繼續迭代:將當前結點彈出棧並推入子結點。每一步都會更新深度。
複雜度分析
show me the code
class Solution: def maxDepth(self, root): """ :type root: TreeNode :rtype: int """ stack = [] 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