題目概要
判斷一個二元樹的最大深度為多少。
![[JavaScript] LeetCode 104. Maximum Depth of Binary Tree XXmy0yX XXmy0yX [JavaScript] LeetCode 104. Maximum Depth of Binary Tree](https://i.imgur.com/XXmy0yX.png)
解題技巧
- 只要有一個節點就算一層,用遞迴解。
- 每層只要節點數不為零就 +1,並且加上左右父節點最大深度。
程式碼
/** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */ /** * @param {TreeNode} root * @return {number} */ var maxDepth = function(root) { if (!root) return 0; return 1 + Math.max(maxDepth(root.left), maxDepth(root.right)) };
![[JavaScript] LeetCode 104. Maximum Depth of Binary Tree image 3 image 3 [JavaScript] LeetCode 104. Maximum Depth of Binary Tree](https://namepluto.com/wp-content/uploads/2022/04/image-3.png)
Latest posts by pluto (see all)
- 解決 preact-router 資源請求路徑錯誤的問題 - 2022 年 6 月 24 日
- [楓之谷私服] 潮流轉蛋機 NPC 腳本優化 - 2022 年 6 月 19 日
- [楓之谷私服] 簡單的飛天椅子(坐騎)改法 v120 - 2022 年 6 月 19 日