# 104. Maximum Depth of Binary Tree

## 递归

class Solution {
public:
int maxDepth(TreeNode* root) {
if(root==0)
return 0;
return 1+max(maxDepth(root->left), maxDepth(root->right));/*root!=NULL depth>=1*/
}
};

## DFS

class Solution {
public:
int maxDepth(TreeNode* root) {
if(root==NULL)
return 0;
stack<TreeNode*> nodes; //save traversal nodes
int result=0;   //save max depth of node
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;
}
};

• 本文已收录于以下专栏：

举报原因： 您举报文章：104. Maximum Depth of Binary Tree 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)