使用层遍历法计算二叉树的调试
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution{
public:
int maxDepth(TreeNode * root)
{
int depth=0;
if(root==NULL)
return 0;
vector<TreeNode *>vec;
vec.push_back(root);
int cur=0;
int last=1;
while(cur<vec.size())
{
last=vec.size();
while(cur<last)
{
if(vec[cur]->left)
vec.push_back(vec[cur]->left);
if(vec[cur]->right)
vec.push_back(vec[cur]->right);
++cur;
}
++depth;
}
return depth;
}
};
使用队列计算二叉树调试,在队列中加入一个结束符号NULL,即在每一行结束处加入NULL,在遍历的过程中,遇到NULL深度增加,当队列为空时结束搜索
class Solution{
public:
int maxDepth(TreeNode *root)
{
if(root==NULL)
return 0;
int depth=0;
queue<TreeNode*> q;
TreeNode *p;
q.push(root);
q.push(NULL);
while(true)
{
p=q.front();
q.pop();
if(p)
{
if(p->left)
q.push(p->left);
if(p->right)
q.push(p->right);
}
else
{
++depth;
if(q.empty())
break;
q.push(NULL);
}
}
return depth;
}
};