欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

PAT1147heaps-二叉树的后序遍历+vector误区点

程序员文章站 2022-05-20 13:52:50
...
先是错误代码,然后改正:
//思路:存入数组,flag判断,后序遍历。

/*
//出现输入一串后再输不进去
#include<bits/stdc++.h>
#define MAXN 1010
using namespace std;

int flag, n;
vector<int> pos;

void postOrder(int now){
    if(now <= (n-1)/2){
        postOrder(now*2);
        postOrder(now*2+1);
    }
    else return;
    if(now == 1)
        cout << pos[now];
    else cout << " " << pos[now];
}

int main(){
    int m;
    cin >> m >> n;
    for(int i = 0; i < m; i++){
        for(int j = 1; j <= n; j++){
            cin >> pos[j];
        }
        flag = pos[1] > pos[2]?1:-1;
        int j;
        for(j = 1; j <= (n-1)/2; j++){
            int left = j*2, right = j*2+1;
            if(flag == 1){
                if(pos[left] > pos[j] || pos[right] > pos[j]){
                    cout << "Not Heap\n";
                    break;
                }
            }else if(flag = -1){
                if(pos[left] < pos[j] || pos[right] < pos[j]){
                    cout << "Not Heap\n";
                    break;
                }
            }
        }
        if(j == (n-1)/2){
            if(flag == 1) cout << "Max Heap\n";
            else cout << "Min Heap\n";
        }
        postOrder(1);
    }
    return 0;
}
*/

//改正:
#include<bits/stdc++.h>
#define MAXN 1010
using namespace std;

int flag, n;
vector<int> pos;

void postOrder(int now){
    if(now > n){
        return ;                //放到下一次递归中处理
    }
    postOrder(now*2);
    postOrder(now*2+1);
    if(now == 1)
        cout << pos[now] << endl;
    else cout<< pos[now] << " "; //注意是后序,因此最后输出第一个元素
}

int main(){
    int m;
    cin >> m >> n;
    //pos.resize(n);             //错因
    for(int i = 0; i < m; i++){
        for(int j = 1; j <= n; j++){
            int num;
            cin >> num;
            pos.push_back(num);
        }
        flag = pos[1] > pos[2]?1:-1;
        int j;
        for(j = 1; j <= (n)/2; j++){
            int left = j*2, right = j*2+1;
            if(right > n) right = left;      //两个测试点不过的原因--->修正然后
            if(flag == 1){
                if(pos[left] > pos[j] || pos[right] > pos[j]){
                    cout << "Not Heap\n";
                    break;
                }
            }else if(flag = -1){
                if(pos[left] < pos[j] || pos[right] < pos[j]){
                    cout << "Not Heap\n";
                    break;
                }
            }
        }
        if(j > n/2){                         //错因:细节的处理要清晰
            if(flag == 1) cout << "Max Heap\n";
            else cout << "Min Heap\n";
        }
        postOrder(1);
    }
    return 0;
}