PAT (Advanced Level) Practice A1115 Counting Nodes in a BST (30 分)(C++)(甲級)(二叉樹、二叉排序樹、層次遍歷)

原題鏈接

#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;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章