C++指针创建完全二叉搜索树(CBT)

参考文章数组格式

,指针形式可以随意指定遍历形式

#include 

using namespace std;

int arr[1010]={0};
struct node
{
    int val;
    struct node *lchild,*rchild;
};

int getLeftLength(int n)
{
    int height = floor(log(n+1)/log(2));
    int x = n+1-pow(2,height);
    x = min(x,(int)pow(2,height-1));
    return ((int)pow(2,height-1)-1+x);
}

node * build(node *root,int Aleft,int Aright)
{
    int n = Aright-Aleft +1;
    if(n==0) return root;
    int L = getLeftLength(n);
    if(root == NULL)
    {
        root = new node();
        root->val = arr[Aleft+L];
        root->lchild = root->rchild = NULL;
    }
    root->lchild = build(root->lchild,Aleft,Aleft+L-1);
    root->rchild = build(root->rchild,Aleft+L+1,Aright);
    return root;
}
vector<int> ans;
void levelOrder(node *root)
{
    if(root == NULL) return;
    queue<node*> q;
    q.push(root);
    while(!q.empty())
    {
        root = q.front();
        ans.push_back(root->val);
        q.pop();
        if(root->lchild!=NULL) q.push(root->lchild);
        if(root->rchild!=NULL) q.push(root->rchild);
    }
}

int main()
{
    struct node *root = NULL;
    int n;
    scanf("%d",&n);
    for(int i=0;i<n;i++) scanf("%d",&arr[i]);
    sort(arr,arr+n);
    root = build(root,0,n-1);
    levelOrder(root);
    for(int i=0;i<ans.size();i++) 
    {
        printf("%d",ans[i]);
        if(i!=ans.size()-1) printf(" ");
    }
    return 0;
}

你可能感兴趣的:(PAT,甲级)