解題思路 :
從 root 開始做 recursive 回傳以左右兩邊 child 為起點的高度 取最大的一邊加上 1 (root本身) 如果 root 本身是 nullptr 就回傳 0
C++ code :
<pre><code>
/**
- Definition of TreeNode:
- class TreeNode {
- public:
int val;
TreeNode *left, *right;
TreeNode(int val) {
this->val = val;
this->left = this->right = NULL;
}
- }
*/
class Solution {
public:
/**
* @param root: The root of binary tree.
* @return: An integer
*/
int maxDepth(TreeNode *root) {
// write your code here
if(root == nullptr) return 0;
else return 1 + max(maxDepth(root->left), maxDepth(root->right));
}
};
<code><pre>