一、技术总结
- 本题是一个排序二叉树问题,题意理解起来就是,给N个结点,将其生成排序二叉树,然后将最后两层的结点数统计加以输出。
- 关键就是一个insert函数的书写,以及使用一个num数组进行存储每一层的结点数,使用DFS深度搜索遍历,传参包括一个root排序二叉树,一个depth用于记录该结点的层数初始为0层。
- 使用maxdepth记录最大层数。
- 最后将num数组中的最后两层输出。
二、参考代码
#include<bits/stdc++.h>
using namespace std;
struct node{
int data;
node* rchild;
node* lchild;
};
void insert(node* &root, int x){
if(root == NULL){
root = new node;
root->data = x;
root->rchild = root->lchild = NULL;
return;
}else if(x <= root->data){
insert(root->lchild, x);
}else{
insert(root->rchild, x);
}
}
vector<int> num(1000);
int maxdepth = -1;
void dfs(node* root, int depth){
if(root == NULL){
maxdepth = max(depth, maxdepth);
return;
}
num[depth]++;
dfs(root->lchild, depth+1);
dfs(root->rchild, depth+1);
}
int main(){
int n, data;
scanf("%d", &n);
node* root = NULL;
for(int i = 0; i < n; i++){
scanf("%d", &data);
insert(root, data);
}
dfs(root, 0);
printf("%d + %d = %d", num[maxdepth-1], num[maxdepth-2], num[maxdepth-1] + num[maxdepth-2]);
return 0;
}
三、排序二叉树的基本操作
//注释部分为排序二叉树的一些基本操作
/*
node* newNode(int v){
node* Node = new node;
Node->data = v;
Node->lchild = Node->rchild = NULL;
return Node;
}
void insert(node* &root, int x){
if(root == NULL){
root = newNode(x);
return;
}
if(x == root->data){
return;
}else if(x < root->data){
insert(root->lchild, x);
}else{
insert(root->rchild, x);
}
}
node* Create(int data[], int n){
node* root = NULL;
for(int i = 0; i < n; i++){
insert(root, data[i]);
}
return root;
}
node* findMax(node* root){
while(root->rchild != NULL){
root = root->rchild;
}
return root;
}
node* findMin(node* root){
while(root->lchild != NULL){
root = root->lchild;
}
return root;
}
void deleteNode(node* &root, int x){
if(root == NULL) return;
if(root->data == x){
if(root->lchild == NULL && root->rchild == NULL){
root = NULL;
}else if(root->lchild != NULL){
node* pre = findMax(root->lchild);
root->data = pre->data;
deleteNode(root->lchild, pre->data);
}else{
node* next = findMin(root->rchild);
root->data = next->data;
deleteNode(root->rchild, next->data);
}
}else if(root->data > x){
deleteNode(root->lchild, x);
}else{
deleteNode(root->rchild, x);
}
}
*/