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.
#include <bits/stdc++.h>
using namespace std;
struct node{
int data;
node*left=NULL;
node*right=NULL;
};
node* creatnode(int data){
node*temp=new node;
temp->data=data;
return temp;
}
node* insert(node*root,node*temp){
if(root==NULL)
return NULL;
if(temp->data<root->data){
temp->left=root;
root=temp;
}
else if(temp->data>root->data&&root->right==NULL)
root->right=temp;
else if(temp->data>root->data&&root->right!=NULL){
root->right=insert(root->right,temp);
}
return root;
}
vector<int>v;
void levelorder(node *root){
if(root==NULL)
return;
queue<node*>que;
que.push(root);
while (!que.empty()){
node* temp=que.front();
v.push_back(temp->data);
que.pop();
if(temp->left!=NULL)
que.push(temp->left);
if(temp->right!=NULL)
que.push(temp->right);
}
}
int main() {
node* root;
int n;cin>>n;
int first;cin>>first;
root= creatnode(first);
for(int i=0;i<n-1;i++){
int data;cin>>data;
node* temp= creatnode(data);
root= insert(root,temp);
}
levelorder(root);
for(int i=0;i<v.size();i++){
if(i==0)
cout<<v[i];
else
cout<<" "<<v[i];
}
}