PAT (Advanced Level) Practice A1115 Counting Nodes in a BST (30 分)(C++)(甲级)(二叉树、二叉排序树、层次遍历)

版权声明:假装有个原创声明……虽然少许博文不属于完全原创,但也是自己辛辛苦苦总结的,转载请注明出处,感谢! https://blog.csdn.net/m0_37454852/article/details/88419499

原题链接

#include <algorithm>
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <ctime>
#include <cstring>
#include <string>
#include <vector>
#include <set>
#include <map>
#include <stack>
#include <queue>
#include <deque>
using namespace std;

const int MAX = 10010, INF = 1<<30;

typedef struct BiTNode
{
    int data, level;//数据及其所在的层次
    struct BiTNode *lChild, *rChild;//左右孩子指针
}BiTNode, *BiTree;

BiTree newNode(int X)//新建一个数据为X的指针
{
    BiTree T = new BiTNode;
    T->data = X;
    T->lChild = NULL;
    T->rChild = NULL;
    return T;
}

void insertNode(BiTree &T, int X)//在T节点上插入数据为X
{
    if(!T) T = newNode(X);
    else if(X <= T->data) insertNode(T->lChild, X);
    else insertNode(T->rChild, X);
}

void BFS(BiTree T, int &num_now, int &num_last)//BFS遍历,num_now和num_last存储本层和上一次元素个数
{
    queue<BiTree> Q;
    Q.push(T);
    T->level = 1;
    int t_level = 0;
    while(!Q.empty())
    {
        T = Q.front();
        Q.pop();
        //printf("%d_", T->data);
        if(T->level - t_level == 2)
        {
            num_last = num_now;
            num_now = 0;
            t_level++;
        }
        num_now++;
        if(T->lChild)
        {
            Q.push(T->lChild);
            T->lChild->level = T->level + 1;
        }
        if(T->rChild)
        {
            Q.push(T->rChild);
            T->rChild->level = T->level + 1;
        }
    }
}

int main()
{
    int N, X;
    int n1 = 0, n2 = 0;
    BiTree ROOT = NULL;
    scanf("%d", &N);
    for(int i=0; i<N; i++)
    {
        scanf("%d", &X);
        insertNode(ROOT, X);//建树
    }
    BFS(ROOT, n1, n2);
    printf("%d + %d = %d", n1, n2, n1+n2);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/m0_37454852/article/details/88419499