1. 程式人生 > >PAT (Advanced Level) Practice 1115 Counting Nodes in a BST (30 分)

PAT (Advanced Level) Practice 1115 Counting Nodes in a BST (30 分)

排序二叉樹,注意看定義

#include<cstdio>
using namespace std;

const int N=1e3+5;

int ch[N][2],key[N],rt,dfn,level[N];

void insert(int x)
{
    key[++dfn]=x;
    if(rt==-1){rt=dfn;return;}
    int now=rt,pre;
    while(now)
    {
        pre=now;
        if(x<=key[now]) now=ch[now][0];
        else
now=ch[now][1]; } if(x<=key[pre]) ch[pre][0]=dfn; else ch[pre][1]=dfn; } void dfs(int u,int lev) { level[lev]++; if(ch[u][0]) dfs(ch[u][0],lev+1); if(ch[u][1]) dfs(ch[u][1],lev+1); } int main() { int n;scanf("%d",&n); rt=-1,dfn=0; for(int i=1;i<=n;i++) {
int x;scanf("%d",&x); insert(x); } dfs(rt,1); int cnt=0,p[5]; for(int i=N-1;i>=1&&cnt<2;i--) if(level[i]) p[cnt++]=level[i]; printf("%d + %d = %d\n",p[0],p[1],p[0]+p[1]); return 0; }