PAT甲题题解-1064. Complete Binary Search Tree (30)-中序和层次遍历,水

由于是满二叉树,用数组既可以表示
父节点是i,则左孩子是2*i,右孩子是2*i+1
另外根据二分搜索树的性质,中序遍历恰好是从小到大排序
因此先中序遍历填充节点对应的值,然后再层次遍历输出即可。

又是一道遍历的水题。。。

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <string.h>
#include <queue>
using namespace std;
const int maxn=1005;
int a[maxn];
int node[maxn];
int cnt=0;
void build(int root,int n){
    if(cnt>n)
        return;
    if(root>n)
        return;
    build(root<<1,n);
    node[root]=a[++cnt];
//printf("id:%d val:%d\n",root,node[root]);
    build((root<<1)|1,n);
}
void BFS(int root,int n){
    queue<int> q;
    q.push(root);
    int v;
    bool first=true;
    while(!q.empty()){
        v=q.front();
        q.pop();
        if(first){
            first=false;
            printf("%d",node[v]);
        }
        else
            printf(" %d",node[v]);
        if(v*2<=n)
            q.push(v*2);
        if(v*2+1<=n)
            q.push(v*2+1);
    }

}
int main()
{
    int n;
    scanf("%d",&n);
    for(int i=1;i<=n;i++)
        scanf("%d",&a[i]);
    sort(a+1,a+n+1);
    build(1,n);
    BFS(1,n);

    return 0;
}
View Code

 

posted @ 2017-03-02 11:35  辰曦~文若  阅读(234)  评论(0编辑  收藏  举报