Python實現(xiàn)二叉樹的最小深度的兩種方法
找到給定二叉樹的最小深度
最小深度是從根節(jié)點到最近葉子節(jié)點的最短路徑上的節(jié)點數(shù)量
注意:葉子節(jié)點沒有子樹
Example:
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its minimum depth = 2.
1:算法遍歷二叉樹每一層,一旦發(fā)現(xiàn)某層的某個結(jié)點無子樹,就返回該層的深度,這個深度就是該二叉樹的最小深度
def minDepth(self, root): """ :type root: TreeNode :rtype: int """ if not root: return 0 curLevelNodeList = [root] minLen = 1 while curLevelNodeList is not []: tempNodeList = [] for node in curLevelNodeList: if not node.left and not node.right: return minLen if node.left is not None: tempNodeList.append(node.left) if node.right is not None: tempNodeList.append(node.right) curLevelNodeList = tempNodeList minLen += 1 return minLen
2:用遞歸解決該題和"二叉樹的最大深度"略有不同。主要區(qū)別在于對“結(jié)點只存在一棵子樹”這種情況的處理,在這種情況下最小深度存在的路徑肯定包括該棵子樹上的結(jié)點
def minDepth(self, root): """ :type root: TreeNode :rtype: int """ if not root: return 0 if not root.left and root.right is not None: return self.minDepth(root.right)+1 if root.left is not None and not root.right: return self.minDepth(root.left)+1 left = self.minDepth(root.left)+1 right = self.minDepth(root.right)+1 return min(left,right)
算法題來自:https://leetcode-cn.com/problems/minimum-depth-of-binary-tree/description/
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Python進(jìn)程間通信 multiProcessing Queue隊列實現(xiàn)詳解
這篇文章主要介紹了python進(jìn)程間通信 mulitiProcessing Queue隊列實現(xiàn)詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2019-09-09Pytorch學(xué)習(xí)筆記DCGAN極簡入門教程
網(wǎng)上GAN的教程太多了,這邊也談一下自己的理解,本文給大家介紹一下GAN的兩部分組成,有需要的朋友可以借鑒參考下,希望能夠有所幫助2021-09-09pyenv與virtualenv安裝實現(xiàn)python多版本多項目管理
這篇文章主要介紹了pyenv與virtualenv安裝實現(xiàn)python多版本多項目管理過程,本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價值,需要的朋友可以參考下2019-08-08Python使用mmap實現(xiàn)內(nèi)存映射文件操作
內(nèi)存映射通??梢蕴岣逫/O的性能,本文主要介紹了Python使用mmap實現(xiàn)內(nèi)存映射文件操作,分享給大家,感興趣的可以了解一下2021-06-06