PAT | A1115 Counting Nodes in a BST

#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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值