題目概要
判斷一個二元樹的最大深度為多少。
解題技巧
- 只要有一個節點就算一層,用遞迴解。
- 每層只要節點數不為零就 +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)) };
Latest posts by pluto (see all)
- React 那些好看、有趣、實用的函式庫、組件庫推薦(2) - 2022 年 6 月 26 日
- 解決 preact 資源請求路徑錯誤的問題 - 2022 年 6 月 24 日
- [楓之谷私服] 潮流轉蛋機 NPC 腳本優化 - 2022 年 6 月 19 日