【Leetcode解題】104. Maximum Depth of Binary Tree
題目
- 題目連結
- 目標函式 :
maxDepth(root)- Input :
root: TreeNode - Output :
int
- Input :
解題概念
- 題意 : 給定一 Binary tree 的
root,需要回傳其最大深度 - Binary tree 最大深度之定義 : 從 Root Node 到最遠 Leaf Node 最長路徑上的節點數量
我的寫法
- 想法 : 這題也是 Binary tree 的經典題型之一,其解法就是
max(node.left, node.right) + 1 - 程式碼 :
1
2
3
4
5def maxDepth(self, root):
if not root: return 0
return max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1 - 成效 :
- Time Complexity : $O(n)$
- Runtime: 27 ms (faster than 56.82%)
- Memory Usage: 15.9 MB (more than 96.7%)
解答 or 其他優秀寫法
- 想法 : 與我的寫法相同
本部落格所有文章除特別聲明外,均採用 CC BY-NC-SA 4.0 許可協議。轉載請註明來自 Robin's Tech Blog!


