[Computer PubMed 408] (binary tree + heap) (interorder traversal + layer order traversal) is very suitable for 408 algorithm questions to investigate a PAT class A question 1167 Cartesian Tree

Title meaning

Give you an in-order traversal of the minimum heap, and ask you to output its level-order traversal

answer

  1. Build a binary tree
  2. sequence traversal
#include <bits/stdc++.h>
using namespace std;

typedef struct BitNode{
    
    
    int data;
    struct BitNode *lchild, *rchild;
}BitNode, *BitTree;
int v[35];

void create(BitTree &p, int L, int R){
    
    
    if (L > R) return;
    int minidx = L;
    for(int i = L; i <= R; i++){
    
    
        if (v[i] < v[minidx]){
    
    
            minidx = i;
        }
    }
    p = (BitTree)malloc(sizeof(BitNode));
    p->data = v[minidx];
    //cout << v[minidx] << '\n';
    create(p->lchild, L, minidx - 1);
    create(p->rchild, minidx + 1, R);
}

int main(){
    
    
    int n; cin >> n;
    //输入的是中序遍历最小堆的情况
    for(int i = 0; i < n; i++){
    
    
        cin >> v[i];
    }
    BitTree ans;
    create(ans, 0, n-1);
    
    //层序遍历
    queue<BitTree> q;
    q.push(ans);
    bool firstprint = true;
    while(!q.empty()){
    
    
        BitTree temp = q.front();
        if (firstprint){
    
    
            cout << temp->data;
            firstprint = false;
        }
        else {
    
    
            cout << " " << temp->data;
        }
        if(temp->lchild != NULL)
            q.push(temp->lchild);
        if (temp->rchild != NULL)
            q.push(temp->rchild);
        
        q.pop();
        
    }
    cout << '\n';
}

Guess you like

Origin blog.csdn.net/qq_43382350/article/details/129316987