#include <iostream>
#include <vector>
#include <queue>
using namespace std;
struct Node{
int data;
int lchild,rchild;
};
vector<Node> nodes;
int lowest = 0;
int secondLowest = 0;
void insert(int x){
if(nodes.size() == 1)
return;
bool successInsert = false;
int i = 0;
while(!successInsert){
if(x <= nodes[i].data){ // x应该插入该节点的左子树中
if(nodes[i].lchild == -1){
nodes[i].lchild = nodes.size() - 1;
successInsert = true;
}else{
i = nodes[i].lchild;
}
}else{ // x应插入该节点的右子树
if(nodes[i].rchild == -1){
nodes[i].rchild = nodes.size() - 1;
successInsert = true;
}else{
i = nodes[i].rchild;
}
}
}
return;
}
void trav(int root){
queue<int> q;
q.push(root);
int curLevelNum = 1;
int nextLevelNum = 0;
lowest = curLevelNum;
while(!q.empty()){
int u = q.front();
q.pop();
if(nodes[u].lchild != -1){
q.push(nodes[u].lchild);
nextLevelNum++;
}
if(nodes[u].rchild != -1){
q.push(nodes[u].rchild);
nextLevelNum++;
}
curLevelNum--;
if(curLevelNum == 0 && nextLevelNum != 0){
secondLowest = lowest;
lowest = nextLevelNum;
curLevelNum = nextLevelNum;
nextLevelNum = 0;
}
}
}
int main(){
int n;
scanf("%d",&n);
for(int i = 0;i < n;i++){
int x;
scanf("%d",&x);
Node temp;
temp.data = x;
temp.lchild = -1;
temp.rchild = -1;
nodes.push_back(temp);
insert(x);
}
trav(0);
printf("%d + %d = %d",lowest,secondLowest,lowest + secondLowest);
system("pause");
return 0;
}
PAT | A1115 Counting Nodes in a BST
最新推荐文章于 2024-09-29 18:03:50 发布