A Cartesian tree is a binary tree constructed from a sequence of distinct numbers. The tree is heap-ordered, and an inorder traversal returns the original sequence. For example, given the sequence { 8, 15, 3, 4, 1, 5, 12, 10, 18, 6 }, the min-heap Cartesian tree is shown by the figure.
CTree.jpg
Your job is to output the level-order traversal sequence of the min-heap Cartesian tree.
Input Specification:
Each input file contains one test case. Each case starts from giving a positive integer N (≤30), and then N distinct numbers in the next line, separated by a space. All the numbers are in the range of int.
Output Specification:
For each test case, print in a line the level-order traversal sequence of the min-heap Cartesian tree. All the numbers in a line must be separated by exactly one space, and there must be no extra space at the beginning or the end of the line.
Sample Input:
10
8 15 3 4 1 5 12 10 18 6
Sample Output:
1 3 5 8 4 6 15 10 12 18
这题也太水了……
以前做过LCA的题,用那个题的建树思路就可以
#include <iostream>
#include <queue>
using namespace std;
const int INF = 100005;
struct Node {
int data;
Node* left,* right;
Node() {left = right = NULL;}
};
int inOrder[INF];
int N;
void build(Node*& root, int inL, int inR) {
if (inL > inR) return ;
int minNum = INF, minSub = inL;
for (int i = inL; i <= inR; i ++) {
if (inOrder[i] < minNum) {
minNum = inOrder[i];
minSub = i;
}
}
int length = minSub - inL; //求长度
if (root == NULL) {
root = new Node();
root->data = minNum;
}
build(root->left, inL, inL + length - 1);
build(root->right, inL + length + 1, inR);
}
void levelT(Node* root) {
queue<Node*> qu;
qu.push(root);
int num = 0;
while (!qu.empty()) {
Node* tNode = qu.front(); qu.pop();
num ++;
if (num < N) cout << tNode->data << " ";
else cout << tNode->data << endl;
if (tNode->left != NULL) qu.push(tNode->left);
if (tNode->right != NULL) qu.push(tNode->right);
}
}
int main() {
cin >> N;
for (int i = 0; i < N; i ++) cin >> inOrder[i];
Node* root = NULL;
build(root, 0, N - 1);
levelT(root);
cin >> N;
return 0;
}