1064 Complete Binary Search Tree (30 分) 技巧性➕排序树性质

这样插入的排序树很不平衡,不是题目中的fill树。
1⃣️排序树的中序遍历结果是有序的,所以可以先排序,在中序列遍历的时候插值
2⃣️用树的静态写法,那除了叶子都是满的,符合题目要求。
3⃣️层次遍历结果和结点数组顺序一样。!!!才发现

#include<iostream>
#include<vector>
#include<queue>
using namespace std;
struct node{
    
    
    int data;
    node *left,*right;
};
void insert(node* &root,int data){
    
    
    if(root==NULL){
    
    
        root=new node;
        root->data=data;
        //cout<<data<<" ";
        root->left=root->right=NULL;
        return;
    }
    if(data<root->data) insert(root->left,data);
    else insert(root->right,data);
}
void laverorder(node* root,vector<int> &v){
    
    
    if(root==NULL) return;
    queue<node*> q;
    q.push(root);
    while(!q.empty()){
    
    
        node* temp=q.front();
        v.push_back(temp->data);
        q.pop();
        if(temp->left!=NULL) q.push(temp->left);
        if(temp->right!=NULL) q.push(temp->right);
    }
}
int N;
int main(){
    
    
    int temp;
    vector<int> v;
    node* root=NULL;
    cin>>N;
    for(int i=0;i<N;i++){
    
    
        cin>>temp;
        insert(root,temp);
    }
    laverorder(root,v);
    cout<<v[0];
    for(int i=1;i<v.size();i++){
    
    
        cout<<" "<<v[i];
    }
    return 0;
}

静态树2x 与 2x+1这个性质,适合树的左右孩子连续编号的情况。2⃣️添加node,适合题目给出左右孩子地址下标

#include<iostream>
#include<algorithm>
using namespace std;
const int maxn=1010;
int n,number[maxn],CBT[maxn],index=0;
void inorder(int root){
    
    
    if(root>n) return;
    inorder(root*2);
    CBT[root]=number[index++];
    inorder(root*2+1);
}
int main(){
    
    
    cin>>n;
    for(int i=0;i<n;i++){
    
    
        cin>>number[i];
    }
    sort(number,number+n);
    inorder(1);
    for(int i=1;i<=n;i++){
    
    
        cout<<CBT[i];
        if(i<n) cout<<" ";
    }
    return 0;
}


猜你喜欢

转载自blog.csdn.net/qq_42835526/article/details/113742432