# PAT_甲级_1115 Counting Nodes in a BST

#### AC代码

``````#include<cstdio>
#include<algorithm>
#include<queue>

using namespace std;

struct Node{
int val;
Node* left;
Node* right;
int level;
};

/// 将x插入到root中
void insert(Node* &root,int x){
if(root== nullptr){
root = new Node;
root->val = x;
root->left = nullptr;
root->right = nullptr;
return;
}
if(root->val<x){
insert(root->right,x);
}else{
insert(root->left,x);
}
}

// 根据数组arr建树
Node* createTree(int arr[],int n){
Node* root = nullptr;
for(int i=0;i<n;++i){
insert(root,arr[i]);
}
return root;
}

int L[1000];// 每一层的节点个数
int maxLevel = -1;

void layerOrder(Node* root){
queue<Node*> que;
root->level = 1;
que.push(root);
while(!que.empty()){
Node* t = que.front();
que.pop();
maxLevel = max(maxLevel,t->level);
++L[t->level];
if(t->left){
t->left->level = t->level + 1;
que.push(t->left);
}
if(t->right){
t->right->level = t->level + 1;
que.push(t->right);
}
}
}

int main() {
int n;
scanf("%d",&n);
int initial[n];
for(int i=0;i<n;++i){
scanf("%d",&initial[i]);
}
Node* root = createTree(initial,n);
layerOrder(root);
printf("%d + %d = %d",L[maxLevel],L[maxLevel-1],L[maxLevel-1]+L[maxLevel]);
return 0;
}
``````

566 声望
15 粉丝
0 条评论