**
解决方法:
**
1.递归
class Solution {
public:
int maxDepth(TreeNode* root) {
int left,right,depth;
if(root==nullptr)
{return 0;}
else
{
left=maxDepth(root->left); //左儿子的最大深度
right=maxDepth(root->right); //右儿子
depth=((left > right) ? left : right);
return depth+1;
}
}
};
2.迭代
抓住层序遍历
class Solution { //层序遍历
public:
int maxDepth(TreeNode* root) {
int res=0;
if(root==NULL)
return 0;
queue<TreeNode*> qu;
qu.push(root);
while(!qu.empty())
{
res++;
int len=qu.size();
for(int i=0;i<len;i++)
{
TreeNode* p=qu.front();
qu.pop();
if(p->left!=nullptr)
qu.push(p->left);
if(p->right!=nullptr)
qu.push(p->right);
}
}
return res;
}
};