PAT目前遇到的分治建树的情况:
case 1:给一个堆(HEAP),让你建树分治建树1–根据堆
case 2: 给前序加中序+前序(后序)确定一棵树分治建树2–前中后3选2
case 3:动态建立二叉排序树(BST)(本题)
注意建立二叉搜索书(BST)时,除了可以根据插入顺序也可以根据前序遍历序列,例如PAT甲级1135 1143
- 注意点:注意参数传递是值传递,在本题中也就是地址复制过去,所以注意递归时,先开辟空间,才能链接起来
#include<bits/stdc++.h>
#include<unordered_set>
#define f(i,a,b) for(int i=a;i<=b;++i)
#define fd(i,a,b) for(int i=a;i>=b;--i)
#define debug(x) cerr<<#x<<": "<<x<<endl;
using namespace std;
typedef long long ll;
struct node {
struct node *l;
struct node *r;
int w;
node() {
this->l = NULL;
this->r = NULL;
this->w = -1001;
}
};
int a[1005];
//考察建链表树
void build(node * u,int x) {
if (u->w== -1001) {
u->w = x;
return;
}
if (x <= u->w) {
if (u->l == NULL)u->l = new node;
build(u->l, x);
}
else {
if (u->r == NULL)u->r = new node;
build(u->r, x);
}
}
//考察dfs
int num[1005];
void dfs(node * u, int x) {
if (u == NULL)return;
num[x]++;
dfs(u->l, x + 1);
dfs(u->r, x + 1);
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("in.txt", "r", stdin);
#endif
int n;cin >> n;
f(i, 1, n)cin >> a[i];
node *root = new node;
root->w = a[1];
f(i, 2, n)build(root, a[i]);
dfs(root, 0);
int fg = 0, a=0, b=0;
fd(i, 1004, 0) {
if (!num[i])continue;
if (fg == 0) {
fg++;
a = num[i];
}
else if (fg == 1) {
b = num[i];
break;
}
}
cout << a << " + " << b << " = " << a + b << endl;
return 0;
}