Tree 使用水平顺序遍历的二叉树俯视图
问题:打印二叉树的俯视图 我的方法是使用水平顺序遍历 符合条件的节点将是特定级别的第一个节点或最后一个节点 中间的任何节点都不能是俯视图的一部分 为什么我的代码失败Tree 使用水平顺序遍历的二叉树俯视图,tree,Tree,问题:打印二叉树的俯视图 我的方法是使用水平顺序遍历 符合条件的节点将是特定级别的第一个节点或最后一个节点 中间的任何节点都不能是俯视图的一部分 为什么我的代码失败 vector<int> topView(struct Node *root) { vector<int> lv,rv,ans; queue<pair<Node *,int>>q; q.push({root,0});
vector<int> topView(struct Node *root)
{
vector<int> lv,rv,ans;
queue<pair<Node *,int>>q;
q.push({root,0});
int maxl=0,maxr=-1;
while(!q.empty()) {
int sz=q.size();
for(int i=0;i<sz;i++) {
auto top1 = q.front();
auto top = top1.first;
int r = top1.second;
q.pop();
if(i==0 and r < maxl){
//cout<<r<<'\n';
lv.push_back(top->data);
maxl=r;
}
if(i==sz-1 and r > maxr){
//cout<<r<<'\n';
rv.push_back(top->data);
maxr=r;
}
if(top->left) q.push({top->left,r-1});
if(top->right) q.push({top->right,r+1});
}
}
reverse(begin(lv),end(lv));
for(auto a:lv)
ans.push_back(a);
for(auto a:rv)
ans.push_back(a);
return ans;
}
vector topView(结构节点*根)
{
向量lv、rv、ans;
queueq;
q、 push({root,0});
int maxl=0,maxr=-1;
而(!q.empty()){
int sz=q.size();
对于(int i=0;i
vector<int> topView(struct Node *root)
{
vector<int> lv,rv,ans;
queue<pair<Node *,int>>q;
q.push({root,0});
int maxl=0,maxr=-1;
while(!q.empty()) {
int sz=q.size();
for(int i=0;i<sz;i++) {
auto top1 = q.front();
auto top = top1.first;
int r = top1.second;
q.pop();
if( r < maxl){
//cout<<r<<'\n';
lv.push_back(top->data);
maxl=r;
}
if( r > maxr){
//cout<<r<<'\n';
rv.push_back(top->data);
maxr=r;
}
if(top->left) q.push({top->left,r-1});
if(top->right) q.push({top->right,r+1});
}
}
reverse(begin(lv),end(lv));
for(auto a:lv)
ans.push_back(a);
for(auto a:rv)
ans.push_back(a);
return ans;
}