A1115 Counting Nodes in a BST [bst/dfs]

在这里插入图片描述

#include<iostream>
#include<vector>
#include<queue>
#include<stack>
#include<string>
#include<math.h>
#include<algorithm>
using namespace std;
const int maxn = 1001;
struct node
{
	int data;
	node* left,* right;
}Node[maxn];
void insert(node* &root, int data)
{
	if (root == NULL)
	{
		root = new node;
		root->data = data;
		root->left = root->right = NULL;
		return;
	}
	if (data <= root->data) insert(root->left, data);
	else insert(root->right, data);
}
int num[maxn] = { 0 }, maxdepth = 0;
void dfs(node* root,int depth)
{
	if (root == NULL) return;
	num[depth]++;
	maxdepth = max(depth, maxdepth);
	dfs(root->left, depth + 1);
	dfs(root->right, depth + 1);
}
int main()
{
	int n,data; cin >> n;
	node* root = NULL;
	for (int i = 0; i < n; i++)
	{
		cin >> data;
		insert(root, data);
	}
	dfs(root, 1);
	int ans = num[maxdepth] + num[maxdepth - 1];
	cout << num[maxdepth] <<" + "<< num[maxdepth - 1]<<" = "<<ans << endl;
}
posted @ 2020-07-26 11:23  _Hsiung  阅读(71)  评论(0编辑  收藏  举报