Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the 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:
int maxDepth(TreeNode* root) {
if(!root)
return 0;
int left = maxDepth(root->left) + 1;
int right = maxDepth(root->right) + 1;
return left > right ? left : right;
}
};