自己的方式是先建树,然后进行层序遍历,记录每层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;
}
来源:CSDN
作者:J_北冥有鱼
链接:https://blog.csdn.net/weixin_35737222/article/details/104064728