# 104. Maximum Depth of Binary Tree ## 題目概要 判斷一個二元樹的最大深度為多少。  ## 解題技巧 - 只要有一個節點就算一層,用遞迴解。 - 每層只要節點數不為零就 +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)) }; ``` 
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up