1. 程式人生 > 程式設計 >Python3實現二叉樹的最大深度

Python3實現二叉樹的最大深度

問題提出:

給定一個二叉樹,找出其最大深度。二叉樹的深度為根節點到最遠葉子節點的最長路徑上的節點數。

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

解決思路:遞迴法求解。從根結點向下遍歷,每遍歷到子節點depth+1。

程式碼實現( ̄▽ ̄):

# Definition for a binary tree node.
# class TreeNode:
#   def __init__(self,x):
#     self.val = x
#     self.left = None
#     self.right = None

class Solution:
  def maxDepth(self,root: TreeNode) -> int:
    if root==None:
      return 0
    count = self.getDepth(root,0)
    return count
  
  def getDepth(self,node,count):
    if node!=None:
      num1 = self.getDepth(node.left,count+1);
      num2 = self.getDepth(node.right,count+1);
      num = num1 if num1>num2 else num2
      return num
    else:
      return count

時間和空間消耗:

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。