通过前序遍历构造二叉查找树,再通过树的层序遍历保存每一层的节点数,最后输出最后两层的节点数即可
//
// main.cpp
// PATA1115
//
// Created by Phoenix on 2018/2/24.
// Copyright © 2018年 Phoenix. All rights reserved.
//
#include <iostream>
#include <cstdio>
#include <queue>
#include <vector>
using namespace std;
int n, num[1010];
struct Node {
int data;
Node *lchild, *rchild;
};
Node* newnode(int x) {
Node* root = new Node;
root->data = x;
root->lchild = root->rchild = NULL;
return root;
}
void insert(Node* &root, int x){
if (root == NULL) {
root = newnode(x);
return;
}
if(x <= root->data) insert(root->lchild, x);
else insert(root->rchild, x);
}
void create(Node* &root, int a[]){
for(int i = 0; i < n; i++) {
insert(root, a[i]);
}
}
vector<int> v;
void levelorder(Node* root) {
queue<Node*> q;
q.push(root);
Node *lastnode = root, *newlastnode = NULL;
int num = 0;
while(!q.empty()) {
Node* top = q.front();
q.pop();
num++;
if(top->lchild) {
q.push(top->lchild);
newlastnode = top->lchild;
}
if(top->rchild) {
q.push(top->rchild);
newlastnode = top->rchild;
}
if(top == lastnode) {
v.push_back(num);
lastnode = newlastnode;
num = 0;
}
}
}
int main(int argc, const char * argv[]) {
scanf("%d", &n);
for(int i = 0; i < n; i++) {
scanf("%d", &num[i]);
}
Node* root = NULL;
create(root, num);
levelorder(root);
int i = v.size();
int a = v[i - 1], b = v[i - 2];
printf("%d + %d = %d\n", a, b, a + b);
return 0;
}