欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python3實(shí)現(xiàn)二叉樹的最大深度

 更新時間:2019年09月30日 14:11:36   作者:心是晴朗的  
這篇文章主要介紹了Python3實(shí)現(xiàn)二叉樹的最大深度, 文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧

問題提出:

給定一個二叉樹,找出其最大深度。二叉樹的深度為根節(jié)點(diǎn)到最遠(yuǎn)葉子節(jié)點(diǎn)的最長路徑上的節(jié)點(diǎn)數(shù)。

說明: 葉子節(jié)點(diǎn)是指沒有子節(jié)點(diǎn)的節(jié)點(diǎn)。

解決思路:遞歸法求解。從根結(jié)點(diǎn)向下遍歷,每遍歷到子節(jié)點(diǎn)depth+1。

代碼實(shí)現(xiàn)( ̄▽ ̄):

# 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

時間和空間消耗:

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論