数据结构+贪心专题
数据结构
树
这是二叉搜索树吗?
题目链接
解题思路:
此题我们知道了二叉搜索树的性质:左子树小于根,右子树大于等于根。
且输入的是前序遍历,则对一个二叉树[l,r]:a[l]是根,[l+1,r]是左右子树范围。
其中,前x项若都小于根,剩下的都大于等于根:则从l+1开始的前x个就是左子树,剩下的都是右子树。如此就分出了左右子树[l1,r1][l2,r2],然后再对左右子树递归即可。
由于输出要后序遍历,则我们只需:递归左子树,递归右子树,存根 (按照后序遍历的顺序)即可。
代码:
#include <iostream>
#include <algorithm>
#include <cstring>
#include <vector>
using namespace std;
const int N = 10010;
int n, flag;
int t[N];
vector<int>ans;
void solve(int l, int r) {
if (r < l)
return ;
int i = l + 1, j = r;
if (!flag) {
while (i <= r && t[i] < t[l]) // 最后停止在大于等于的位置,比正确位置后移了一位
i++;
while (j > l && t[j] >= t[l]) // 最后停在小于的位置,比正确位置前移了一位
j--;
if (i - j != 1) // 只有当两者相差1也就是中间没有元素的时候才正确
return ;
solve(l + 1, i - 1);
solve(j + 1, r);
ans.push_back(t[l]);
} else {
while (i <= r && t[i] >= t[l])
i++;
while (j > l && t[j] < t[l])
j--;
if (i - j != 1)
return ;
solve(l + 1, i - 1);
solve(j + 1, r);
ans.push_back(t[l]);
}
}
int main() {
int f = 0;
cin >> n;
for (int i = 1 ; i <= n ; ++i)
cin >> t[i];
solve(1, n);
if (ans.size() == n) {
puts("YES");
for (auto x : ans) {
if (f)
cout << " ";
cout << x;
f++;
}
} else {
ans.clear();
flag = 1;
solve(1, n);
if (ans.size() == n) {
puts("YES");
for (auto x : ans) {
if (f)
cout << " ";
cout << x, f++;
}
} else
puts("NO");
}
return 0;
}
树的遍历
解题思路:
思路:(1)通过后序遍历找到根结点,再通过根结点在中序遍历的位置找出左子树、右子树。(2)根据左子树在后序遍历结果的顺序,找到左子树的根结点,视左子树为一棵独立的树,转步骤(1)。(3)根据右子树在后序遍历结果的顺序,找到右子树的根结点,视右子树为一棵独立的树,转步骤(1)。
注意点:
函数参数需要一个创建二叉树的指针 ,和后序的左右指针,以及中序的左右指针,5个参数。
代码:
#include <iostream>
#include <algorithm>
#include <cstring>
#include <queue>
#include <cstdlib>
using namespace std;
const int N = 1010;
int n ;
int in[N], nx[N];
typedef struct node {
int val;
struct node *l, *r;
} BitNode, *BiTree;
void build(BiTree &T, int L1, int R1, int L2, int R2) {
T = (BiTree)malloc(sizeof (BitNode));
T->val = nx[R1];
int in_root ;
for (int i = L2 ; i <= R2 ; ++i)
if (in[i] == nx[R1]) {
in_root = i ;
break;
}
if ( in_root - L2 != 0 ) {
build(T->l, L1, L1 + in_root - L2 - 1, L2, in_root - 1);
} else
T->l = NULL;
if (R2 - in_root != 0) {
build(T->r, R1 - (R2 - in_root), R1 - 1, in_root + 1, R2 );
} else
T->r = NULL;
}
void bfs(BiTree T) {
queue<BiTree>q;
q.push(T);
int f = 0;
while (q.size()) {
auto u = q.front();
q.pop();
if (f)
cout << " ";
cout << u->val;
f++;
if (u->l)
q.push(u->l);
if (u->r)
q.push(u ->r);
}
}
int main() {
BiTree t;
cin >> n;
for (int i = 1 ; i <= n ; ++i)
cin >> nx[i];
for (int j = 1; j <= n ; ++j