1167 Cartesian Tree + 堆排序 + 中序遍历 + 层序遍历

PAT链接https://pintia.cn/problem-sets/994805342720868352/exam/problems/1478636026017230848

解题思路:给定中序遍历,你就能知道,元素之间是左右子树的关系。对于每一层递归中的根节点来说,左孩子就是左边序列里面最小的元素,右孩子就是右边序列里面最小的元素。

题解代码

#include<iostream>
#include<vector>
#include<queue>
using namespace std;
int n;
vector<int> arr;
struct Node {
    Node(int data) : data(data), lchild(nullptr), rchild(nullptr) {}
    int data;
    Node *lchild, *rchild;
};
Node *build(int start, int end) {
    if (start > end) return nullptr;
    int root_ind = start;
    for (int i = start; i <= end; i++) {
        if (arr[root_ind] > arr[i]) root_ind = i;
    }
    Node *root = new Node(arr[root_ind]);
    root->lchild = build(start, root_ind - 1);
    root->rchild = build(root_ind + 1, end);
    return root;
}
void levelorder(Node *root) {
    queue<Node *> q;
    q.push(root);
    int start = 0;
    while (q.size()) {
        int size = q.size();
        for (int i = 0; i < size; i++) {
            Node* t = q.front(); q.pop();
            start++ && cout << " ";
            cout << t->data;
            if (t->lchild) q.push(t->lchild);
            if (t->rchild) q.push(t->rchild);
        }
    }
}
int main() {
    cin >> n;
    for (int i = 0; i < n; i++) {
        int num; cin >> num;
        arr.push_back(num);
    }
    Node *root = build(0, n - 1);
    levelorder(root);
    return 0;
}
posted @ 2023-05-07 18:07  江韵阁  阅读(30)  评论(0)    收藏  举报