1167 Cartesian Tree c++

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];
    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值