二叉排序树的建立,加上树的遍历。
#include<cstdio>
using namespace std;
struct node
{
int data;
node *left, *right;
};
void insert(node *&root, int data)
{
if (root == NULL)
{
root = new node;
root->data = data;
root->left = root->right = NULL;
return;
}
else if (data <= root->data) insert(root->left, data);
else insert(root->right, data);
}
int maxdepth = -1;
int num[1000] = { 0 };//记录每一层结点数
void preorder(node* root, int depth)
{
if (root == NULL) return;
num[depth]++;
if (depth > maxdepth) maxdepth = depth;
preorder(root->left, depth + 1);
preorder(root->right, depth + 1);
}
int n;
int main()
{
int temp;
node* root = NULL;
scanf("%d", &n);
for (int i = 0; i < n; i++)
{
scanf("%d", &temp);
insert(root, temp);
}
preorder(root, 1);
int n1 = num[maxdepth], n2 = num[maxdepth - 1];
printf("%d + %d = %d", n1, n2, n1 + n2);
return 0;
}