废话不多说,先看题目:
Given a binary tree, find its maximum depth.
题目意思:就是要求得到二叉树的深度或者高度
学过数据结构对这个肯定不会陌生,典型的递归:
/**
* 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==NULL)
return 0;
else
{
int l=maxDepth(root->left);
int r=maxDepth(root->right);
return r>l?r+1:l+1;
}
}
};