Given a binary tree, find its maximum depth.
The maximum depth isthenumberof nodes along the longest path fromthe root node down tothe farthest leaf node.
代码
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
intdfs(TreeNode* root) {
if (root == NULL)
return0;
return1 + max(dfs(root->left), dfs(root->right));
}
int maxDepth(TreeNode* root) {
return dfs(root);
}
};