# 104. Maximum Depth of Binary Tree ## 題目概要 判斷一個二元樹的最大深度為多少。 ![](https://i.imgur.com/cGEzlkF.png) ## 解題技巧 - 只要有一個節點就算一層,用遞迴解。 - 每層只要節點數不為零就 +1,並且加上左右父節點最大深度。 ## 程式碼 ```javascript= /** * 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)) }; ``` ![](https://i.imgur.com/P0Ce4ip.png)