您的位置:首页 > 其它

104. Maximum Depth of Binary Tree

2016-08-29 00:15 387 查看

递归

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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  binarytree 递归 DFS BFS