深度优先:
int maxdepth(TreeNode*root)
{
if(root==null) return 0;
return max(maxdepth(root->left),maxdepth(root->right))+1;
}
广度优先:
int maxDepth(TreeNode* root) {
if(!root)
return 0;
queue<TreeNode*>v1;
queue<TreeNode*>v2;
int sum=0;
v1.push(root);
while(!v1.empty()||!v2.empty())
{
sum++;
if(!v1.empty())
{
while(!v1.empty())
{
if(v1.front()->left) v2.push(v1.front()->left);
if(v1.front()->right) v2.push(v1.front()->right);
v1.pop();
}
}
else
{
while(!v2.empty())
{
if(v2.front()->left) v1.push(v2.front()->left);
if(v2.front()->right) v1.push(v2.front()->right);
v2.pop();
}
}
}
return sum;
}