1115 Counting Nodes in a BST

╄→尐↘猪︶ㄣ 提交于 2020-01-21 20:49:07

自己的方式是先建树,然后进行层序遍历,记录每层node数量,输出最后两层的个数。但比较麻烦。
网上看到两个相对优秀简洁的算法思路,一是在建树的同时,如果插入节点是左右孩子都不存在,相当于if(root == NULL)的else,那么插入也即增加一个深度,然后在if 语句中用数组记录该深度下插入节点的格式。
二是在建树完成后,用深度优先算法进行快速遍历,带出每层个数

#include <iostream>
#include <queue>
using namespace std;
const int maxn = 1001;
int rec[maxn] = {0};	
struct node{
	int data, layer;
	node *lchild, *rchild;
};
void insert(node* &root, int x){
	if(root == NULL){
		root = new node;
		root->data = x;
		root->lchild = root->rchild = NULL;
		return;
	}
	if(x <= root->data) insert(root->lchild, x);
	else insert(root->rchild, x);
}
void levelorder(node *root){
	queue<node*> q;
	q.push(root);
	root->layer = 0;
	rec[root->layer]++;
	while(!q.empty()){
		node *front = q.front();
		q.pop();
		if(front->lchild != NULL){
			node *temp = front->lchild;
			temp->layer = front->layer + 1;
			rec[temp->layer]++;
			q.push(temp); 
		} 
		if(front->rchild != NULL){
			node *temp = front->rchild;
			temp->layer = front->layer + 1;
			rec[temp->layer]++;
			q.push(temp); 
		} 
	}
}
int main(){
	int n, num;
	cin >> n;
	node *root = NULL;
	for(int i = 0; i < n; i++){
		cin >> num;
		insert(root, num);
	}
	levelorder(root);
	int i = 0;
	while(rec[i] != 0) i++;
	printf("%d + %d = %d", rec[i - 1], rec[i - 2], rec[i - 1] + rec[i - 2]);
	return 0;
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!