https://pintia.cn/problem-sets/994805342720868352/problems/994805355987451904
AC代码:
一开始考虑错n1,n2的值,结果只得了2分,而后看大佬代码,发现问题。
我用的是层次遍历,先给每层结点赋上层次值,然后再先序遍历,记录n1与n2,然后给出答案,
#include <iostream>
#include <cstdio>
#include <queue>
#include <algorithm>
using namespace std;
const int maxn = 1010;
struct node {
int data;
node* lchild;
node* rchild;
int layer;
};
node* newNode(int val) {
node* Node = new node;
Node->data = val;
Node->lchild = Node->rchild = NULL;
return Node;
}
void insert(node* &root, int x) {
if (root == NULL) {
root = newNode(x);
return;
}
if (x == root->data) {
insert(root->lchild, x);
}
else if (x < root->data) {
insert(root->lchild, x);
}
else {
insert(root->rchild, x);
}
}
int max_layer = 1, n1, n2;
void LayerOrder(node* root) {
queue<node*> q;
root->layer = 1;
q.push(root);
while (!q.empty()) {
node* now = q.front();
q.pop();
max_layer = max(max_layer, now->layer);
if (now->lchild != NULL) {
now->lchild->layer = now->layer + 1;
q.push(now->lchild);
}
if (now->rchild != NULL) {
now->rchild->layer = now->layer + 1;
q.push(now->rchild);
}
}
}
void preOrder(node* root) {
if (root == NULL)
return;
if (root->layer == max_layer )
n1++;
if (root->layer == max_layer - 1)
n2++;
preOrder(root->lchild);
preOrder(root->rchild);
}
int main() {
int n, data;
node* root = NULL;
scanf_s("%d", &n);
for (int i = 0; i < n; i++) {
scanf_s("%d", &data);
insert(root, data);
}
LayerOrder(root);
preOrder(root);
printf("%d + %d = %d", n1, n2, n1 + n2);
return 0;
}
大家的方案都是用DFS,
#include <iostream>
#include <cstdio>
#include <queue>
#include <algorithm>
using namespace std;
const int maxn = 1010;
struct node {
int data;
node* lchild;
node* rchild;
/// int layer;
};
node* newNode(int val) {
node* Node = new node;
Node->data = val;
Node->lchild = Node->rchild = NULL;
return Node;
}
void insert(node* &root, int x) {
if (root == NULL) {
root = newNode(x);
return;
}
if (x == root->data) {
insert(root->lchild, x);
}
else if (x < root->data) {
insert(root->lchild, x);
}
else {
insert(root->rchild, x);
}
}
int maxdepth = -1;
vector<int> v(1010);
void dfs(node* root, int h) {
if (root == NULL)
return;
maxdepth = max(h, maxdepth);
v[h]++;
dfs(root->lchild, h + 1);
dfs(root->rchild, h + 1);
return;
}
int main() {
int n, x;
node* root = NULL;
scanf_s("%d", &n);
for (int i = 0; i < n; i++) {
scanf_s("%d", &x);
insert(root, x);
}
dfs(root, 0);
printf("%d + %d = %d", v[maxdepth], v[maxdepth - 1], v[maxdepth] + v[maxdepth - 1]);
}