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

Posted Fighting Heart

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了PAT (Advanced Level) 1115. Counting Nodes in a BST (30)相关的知识,希望对你有一定的参考价值。

简单题。统计一下即可。

#include<cstdio>
#include<cstring>
#include<cmath>
#include<vector>
#include<map>
#include<queue>
#include<stack>
#include<algorithm>
using namespace std;

const int maxn=100000+10;
struct Node
{
    int left;
    int right;
    int val;
    int dep;
} s[maxn];

int n;
int a[maxn];
int max_dep,n1,n2;

void dfs(int x,int dep)
{
    max_dep=max(max_dep,dep);
    s[x].dep=dep;
    if(s[x].left!=-1) dfs(s[x].left,dep+1);
    if(s[x].right!=-1) dfs(s[x].right,dep+1);
}

void DFS(int x)
{
    if(s[x].dep==max_dep) n1++;
    else if(s[x].dep==max_dep-1) n2++;
    if(s[x].left!=-1) DFS(s[x].left);
    if(s[x].right!=-1) DFS(s[x].right);
}

int main()
{
    scanf("%d",&n);

    if(n==0) printf("0 + 0 = 0\n");
    else
    {
        for(int i=1; i<=n; i++) scanf("%d",&a[i]);

        for(int i=0; i<=n; i++) s[i].left=s[i].right=-1;
        int id=0;
        s[id++].val=a[1];

        for(int i=2; i<=n; i++)
        {
            int now=0;
            while(1)
            {
                if(a[i]<=s[now].val)
                {
                    if(s[now].left!=-1) now=s[now].left;
                    else
                    {
                        s[now].left=id;
                        s[id++].val=a[i];
                        break;
                    }
                }

                else
                {
                    if(s[now].right!=-1) now=s[now].right;
                    else
                    {
                        s[now].right=id;
                        s[id++].val=a[i];
                        break;
                    }
                }
            }
        }

        max_dep=n1=n2=0;
        dfs(0,1);
        DFS(0);
        printf("%d + %d = %d\n",n1,n2,n1+n2);
    }
    return 0;
}

 

以上是关于PAT (Advanced Level) 1115. Counting Nodes in a BST (30)的主要内容,如果未能解决你的问题,请参考以下文章

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

PAT Advanced Level 1044

PAT Advanced Level 1043

PAT Advanced Level 1079

PAT Advanced Level 1095

PAT Advanced Level 1038