104. 二叉樹的最大深度

問題描述

給定一個二叉樹,找出其最大深度。python

二叉樹的深度爲根節點到最遠葉子節點的最長路徑上的節點數。app

說明: 葉子節點是指沒有子節點的節點。code

示例:
給定二叉樹 [3,9,20,null,null,15,7]遞歸

3
   / \
  9  20
    /  \
   15   7

返回它的最大深度 3 。io

解決方案

方法一:遞歸

利用遞歸的深度優先搜索class

複雜度分析二叉樹

  • 時間複雜度:咱們每一個結點只訪問一次,所以時間複雜度爲 O(N), 其中 NN 是結點的數量。
  • 空間複雜度:在最糟糕的狀況下,樹是徹底不平衡的,例如每一個結點只剩下左子結點,遞歸將會被調用 NN 次(樹的高度),所以保持調用棧的存儲將是O(N)。但在最好的狀況下(樹是徹底平衡的),樹的高度將是 log(N)。所以,在這種狀況下的空間複雜度將是 O(log(N))。

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 的棧開始。而後咱們繼續迭代:將當前結點彈出棧並推入子結點。每一步都會更新深度。

複雜度分析

  • 時間複雜度:O(N).
  • 空間複雜度:O(N).

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
相關文章
相關標籤/搜索