递归
class Solution {
public:
int maxDepth(TreeNode* root) {
if(root==0)
return 0;
return 1+max(maxDepth(root->left), maxDepth(root->right));
}
};
DFS
class Solution {
public:
int maxDepth(TreeNode* root) {
if(root==NULL)
return 0;
stack<TreeNode*> nodes;
int result=0;
nodes.push(root);
root->val=1;
while(nodes.size()>0)
{
TreeNode* top=nodes.top();
nodes.pop();
int curDepth=top->val;
result=result>curDepth?result:curDepth;
if(top->left!=NULL)
{
nodes.push(top->left);
top->left->val=curDepth+1;
}
if(top->right!=NULL)
{
nodes.push(top->right);
top->right->val=curDepth+1;
}
}
return result;
}
};
BFS
class Solution {
public:
int maxDepth(TreeNode* root) {
if(root==NULL)
return 0;
queue<TreeNode*> nodes;
nodes.push(root);
root->val=1;
int result=0;
while(nodes.size())
{
TreeNode *fro=nodes.front();
int curdepth=fro->val;
nodes.pop();
result=result>curdepth?result:curdepth;
if(fro->left)
{
nodes.push(fro->left);
fro->left->val=curdepth+1;
}
if(fro->right)
{
nodes.push(fro->right);
fro->right->val=curdepth+1;
}
}
return result;
}
};