专题复习七(9.9):树专题
1 树与二叉树
常用性质:
-
树的层次(layer)从根节点算起,根节点为第一层。
-
对有n个节点的树,边数一定是n-1;满足连通,边数等于顶点数减1的结构一定是一棵树。
-
节点的子树个数称为节点的度,叶子节点的度为0,当一棵树只有根节点时,根节点也算作叶子节点。
-
根节点深度为1,最底层叶子节点高度为1,对于树来说深度和高度是相等的,但具体到某个节点来说就不一定了。
-
森林(forest) 是若干棵树的集合。
-
二叉树与度为2的树区别在于:二叉树的左右子树是严格区分的,不能随意交换。
-
满二叉树:每一层的节点个数都达到了当层能达到的最大值。完全二叉树:除最下面一层外都达到最大值,且最下面一层也只能从左到右连续存在若干节点。
普通二叉树的存储结构与基本操作:
struct Node{
int data;
Node* lchild;
Node* rchild;
};
//如果知道最大节点个数,也可以使用静态写法:
struct Node{
int data, lchild, rchild;
}node[MAXN];
//如果不是二叉树,可以这样写:
struct Node{
int data;
vector<int> child;
}node[MAXN];
Node* root = NULL;
Node* newNode(int v){
Node* temp = new Node;
temp->data = v;
temp->lchild = temp->rchild = NULL;
return temp;
}
//静态写法:
int index = 0;
int newNode(int v){
node[index].data = v;
node[index].lchild = node[index].rchild = -1;
return index++;
}
//找到并修改所有数据域为x的结点
void search(Node* root, int x, int newData){
if(root == NULL) return;
if(root->data == x) root->data = newData;
search(root->lchild, x, newData);
search(root->rchild, x, newData);
return;
}
//插入的点就是查找失败的地方, 注意传入root的时候要传引用
void insert(Node* &root, int x){
if(root == NULL){
root = newNode(x);
return;
}
if(由二叉树的性质,应该插在左子树){
insert(root->lchild, x);
}
else{
insert(root->rchild, x);
}
return;
}
完全二叉树的存储结构:直接用数组存储,根节点下标为1,左孩子为2x,右孩子为2x+1。
判断是否为叶节点:2x > n则为叶节点。
判断是否为空节点:x > n则为空节点。
2 二叉树的遍历
//先序遍历
void preorder(Node* root){
if(root == NULL) return;
printf("%d\n",root->data);
preorder(root->lchild);
preorder(root->rchild);
}
//中序遍历
void inorder(Node* root){
if(root == NULL) return;
inorder(root->lchild);
printf("%d\n",root->data);
inorder(root->rchild);
}
//后序遍历
void postorder(Node* root){
if(root == NULL) return;
postorder(root->lchild);
postorder(root->rchild);
printf("%d\n",root->data);
}
//层序遍历
void levelorder(Node* root){
if(root == NULL) return;
queue<Node*> q;
root->layer = 1;
q.push(root);
while(!q.empty()){
Node* x = q.front();
q.pop();
printf("%d\n",x->data);
if(x->lchild){
x->lchild->layer = x->layer + 1;
q.push(x->lchild);
}
if(x->rchild){
x->rchild->layer = x->layer + 1;
q.push(x->rchild);
}
}
}
2.1 先序中序建树
Node* create(int preL, int preR, int inL, int inR){
if(preL > preR) return NULL;
Node* root = new Node;
root->data = pre[preL];
int k = inL;
while(in[k] != pre[preL]) k++;
int numLeft = k - inL;
root->lchild = create(preL+1, preL+numLeft, inL, k-1);
root->rchild = create(preL+numLeft+1, preR, k+1, inR);
return root;
}
2.2 后序中序建树
Node* create(int postL, int postR, int inL, int inR){
if(postL > postR) return NULL;
Node* root = new Node;
root->data = post[postR];
int k = inL;
while(in[k] != post[postR]) k++;
int numLeft = k - inL;
root->lchild = create(postL, postL+numLeft-1, inL, k-1);
root->rchild = create(postL+numLeft, postR-1, k+1, inR);
return root;
}
2.3 层序中序建树
//当前二叉树的 层序区间[levelL,levelR], 中序区间[inL,inR]
Node* create(int levelL,int levelR,int inL,int inR) {
//第一步,确定递归边界
if(inL > inR) return NULL;
//第二步,找到当前层序序列中 第一个 出现在当前中序序列的元素 作为根节点root
Node* root = new Node;
int k,flag = 0;
for( ; levelL <= levelR; ++levelL) {//当前层序序列[levelL,levelR]
for(k = inL; k <= inR; ++k) {//当前中序序列 [inL,inR]
if(in[k] == level[levelL]) {
flag = 1; //找到!
break;
}
}
if(flag == 1) break;
}
root->data = level[levelL];
//第三步,确定当前根节点的左子树的层序序列 和中序序列,右子树的层序序列 和中序序列
root->lchild = create(levelL+1,levelR,inL,k-1);
root->rchild = create(levelL+1,levelR,k+1,inR);
return root; //总是忘记这个小可爱~~
}
Node* root = create(0,n-1,0,n-1);
2.4 前序后序求中序(结果不唯一 A1119题)
1119. Pre- and Post-order Traversals (30)-PAT甲级真题(前序后序转中序)_柳婼 の blog-CSDN博客
#include <iostream>
#include <vector>
using namespace std;
vector<int> in, pre, post;
bool unique = true;
void getIn(int preLeft, int preRight, int postLeft, int postRight) {
if(preLeft == preRight) {
in.push_back(pre[preLeft]);
return;
}
if (pre[preLeft] == post[postRight]) {
int i = preLeft + 1;
while (i <= preRight && pre[i] != post[postRight-1]) i++;
if (i - preLeft > 1)
getIn(preLeft + 1, i - 1, postLeft, postLeft + (i - preLeft - 1) - 1);
else
unique = false;
in.push_back(post[postRight]);
getIn(i, preRight, postLeft + (i - preLeft - 1), postRight - 1);
}
}
//或者改成:
void getIn(int preL, int preR, int postL, int postR){
if(preL > preR){
return;
}
if(pre[preL] == post[postR]){
int i = preL + 1;
while(i <= preR && pre[i] != post[postR-1]) i++;
if(i - preL > 1){
getIn(preL + 1, i-1, postL, postL + i - 2 - preL);
}
else if(preL != preR){
Unique = false;
}
in.push_back(pre[preL]);
getIn(i, preR, postL + i - 1 - preL, postR - 1);
}
}
int main() {
int n;
scanf("%d", &n);
pre.resize(n), post.resize(n);
for (int i = 0; i < n; i++)
scanf("%d", &pre[i]);
for (int i = 0; i < n; i++)
scanf("%d", &post[i]);
getIn(0, n-1, 0, n-1);
printf("%s\n%d", unique == true ? "Yes" : "No", in[0]);
for (int i = 1; i < in.size(); i++)
printf(" %d", in[i]);
printf("\n");
return 0;
}
2.5 例题 A1053 Path of Equal Weight (30 分)
树的DFS遍历加剪枝,还是比较经典的。
#include<bits/stdcpp.h>
using namespace std;
const int MAXN = 105;
vector<int> children[MAXN];
int weight[MAXN];
bool hasChild[MAXN] = {0};
vector<int> tempPath;
vector<int> ans[MAXN];
int ansnum = 0;
int n, m, s;
bool cmp(int a, int b){
return weight[a] > weight[b];
}
void DFS(int v, int nowsum){
if(!hasChild[v]){
if(weight[v] + nowsum != s) return;
else{
tempPath.push_back(weight[v]);
ans[ansnum++] = tempPath;
tempPath.pop_back();
return;
}
}
else{
if(weight[v] + nowsum >= s) return;
tempPath.push_back(weight[v]);
for(int i=0; i<children[v].size(); i++){
int child = children[v][i];
DFS(child, nowsum+weight[v]);
}
tempPath.pop_back();
}
return;
}
int main(){
int temproot, num, tempchild;
scanf("%d %d %d",&n,&m,&s);
for(int i=0; i<n; i++){
scanf("%d",&weight[i]);
}
for(int i=0; i<m; i++){
scanf("%d %d",&temproot, &num);
for(int j=0; j<num; j++){
scanf("%d",&tempchild);
children[temproot].push_back(tempchild);
}
hasChild[temproot] = 1;
sort(children[temproot].begin(), children[temproot].end(), cmp);
}
DFS(0,0);
for(int i=0; i<ansnum; i++){
printf("%d", ans[i][0]);
for(int j=1; j<ans[i].size(); j++){
printf(" %d", ans[i][j]);
}
printf("\n");
}
}
3 二叉查找树
注意二叉查找树的递归定义中,空树也是一棵二叉查找树!
左子树上所有结点的数据域均小于等于根节点的数据域,右子树上所有结点的数据域均大于根节点的数据域。
二叉查找树的基本操作:注意即使是一组相同的数字,插入的顺序不同,得到的二叉查找树也会不同。最需要关注的是删除操作。
对二叉查找树进行中序遍历,得到的序列是有序的。
==二叉搜索树的结构(BST)能被单独的先序遍历序列所确定,在结点的数据域均不相同的情况下。==本质上有了先序遍历2 1 3 4,知道2为根,小于2的为左子树,大于2的为右子树,就可以递归下去了。或者按照先序序列插入结点也可以得到这颗二叉树。
struct Node{
int data;
Node* lchild;
Node* rchild;
};
//找到数据域为x的结点,复杂度为O(h),h为二叉搜索树高度
void search(Node* root, int x){
if(root == NULL) printf("没找到");
if(root->data == x) printf("找到啦!");
else if(root->data > x) search(root->lchild, x);
else search(root->rchild, x);
}
//插入的点就是查找失败的地方, 注意传入root的时候要传引用
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);
}
return;
}
//二叉查找树的建立
Node* creare(int data[], int n){
node* root = NULL;
for(int i=0; i<n; i++){
insert(root, data[i]);
}
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 = root->lchild;
while(pre->rchild != NULL) pre = pre->rchild;
root->data = pre->data;
deleteNode(root->lchild, pre->data);
}
else{
Node* next = root->rchild;
while(next->lchild != NULL) next = next->lchild;
root->data = next->data;
deleteNode(root->rchild, next->data);
}
}
else if(root->data > x){
deleteNode(root->lchild, x);
}
else{
deleteNode(root->rchild, x);
}
}
当然这段代码也可以优化,在找到欲删除结点root的后继结点next之后,不进行递归,而直接把结点next的右子树代替结点next成为其父节点的左子树,这样就删去了next。这个优化需要在结点定义中额外记录每个结点的父亲结点地址。
为防止删除后树退化成链,有两种办法:一是每次交替删除前驱或者后继,另一种是记录子树高度,优先在高度较高的子树里删除结点。
3.1 例题 A1043. Is It a Binary Search Tree (25)
有先序的二叉查找树也可以像之前先序中序建树一样,核心思想是找到根节点,再划分左右子树,递归解决。
#include<bits/stdcpp.h>
using namespace std;
const int MAXN = 1005;
int n;
vector<int> post;
int pre[MAXN];
bool isMirror = false;
void getpost(int preL, int preR){
if(preL > preR){
return;
}
int root = pre[preL];
int i = preL + 1, j = preR;
if(isMirror){
while(i <= preR && pre[i] < root) i++;
while(j > preL && pre[j] >= root) j--;
}
else{
while(i <= preR && pre[i] >= root) i++;
while(j > preL && pre[j] < root) j--;
}
if(i-j != 1) return;
else{
getpost(preL+1, j);
getpost(i, preR);
post.push_back(root);
}
}
int main(){
scanf("%d",&n);
for(int i=0; i<n; i++){
scanf("%d",&pre[i]);
}
getpost(0,n-1);
if(post.size() != n){
isMirror = true;
post.clear();
getpost(0,n-1);
}
if(post.size() != n) printf("NO");
else{
printf("YES\n%d",post[0]);
for(int i=1; i<n; i++) printf(" %d",post[i]);
}
}
3.2 例题 7-2 二叉搜索树的插入序列
7-2 二叉搜索树的插入序列_anleeos的博客-CSDN博客
假设一个树的左子树节点数n,左子树符合条件的排列种数为a;其右子树节点数为m,符合条件的排列种数为b。那么该树符合要求的排列总数为
a * b * C(m + n,m); //C(m + n,m)表示从m+n中取m个的组合数。
#include <iostream>
#include <vector>
#define MOD 1000000007
using namespace std;
long C[105][105];
void init()
{
for (int i = 0; i < 105; i++) {
C[i][0] = C[i][i] = 1;
for (int j = 1; j < i; j++) {
C[i][j] = C[i - 1][j] + C[i - 1][j - 1];
C[i][j] %= MOD;
}
}
}
long Cof(long n, long m)
{
if (n < m) swap(n, m);
return C[n][m];
}
long possibility(vector<int> tree)
{
if (tree.size() == 1 || tree.size() == 0) return 1;
vector<int> left, right;
for (int i = 1; i < tree.size(); i++)
if (tree[i] > tree[0]) right.push_back(tree[i]);
else left.push_back(tree[i]);
return possibility(left) % MOD * possibility(right) % MOD * Cof(left.size(), left.size() + right.size()) % MOD;
}
int main()
{
int size;
cin >> size;
if (size == 0) { cout << 0; return 0; }
vector<int> tree;
init();
for (int i = 0; i < size; i++)
{
int temp;
cin >> temp;
tree.push_back(temp);
}
cout << possibility(tree) % MOD;
return 0;
}
3.3 例题A1099 Build A Binary Search Tree (30 分)
中序一定是有序的,利用中序遍历填充值,最后再进行层序遍历输出。
#include<bits/stdcpp.h>
using namespace std;
const int MAXN = 105;
int nowidx = 0;
int n;
int Array[MAXN];
bool firstPrint = true;
struct Node{
int v, lchild, rchild;
}node[MAXN];
void inorder(int idx){
if(idx < 0 || idx >= n) return;
inorder(node[idx].lchild);
node[idx].v = Array[nowidx++];
inorder(node[idx].rchild);
}
void levelorder(int idx){
queue<int> q;
q.push(idx);
while(!q.empty()){
int u = q.front();
q.pop();
if(firstPrint){
firstPrint = false;
printf("%d",node[u].v);
}
else printf(" %d",node[u].v);
if(node[u].lchild != -1) q.push(node[u].lchild);
if(node[u].rchild != -1) q.push(node[u].rchild);
}
}
int main(){
int left, right;
scanf("%d",&n);
for(int i=0; i<n; i++){
scanf("%d %d",&left, &right);
node[i].lchild = left;
node[i].rchild = right;
}
for(int i=0; i<n; i++){
scanf("%d",&Array[i]);
}
sort(Array, Array + n);
inorder(0);
levelorder(0);
}
4 平衡二叉树 (AVL树)
AVL树仍然是一棵二叉查找树,只是增加了平衡的要求,即左子树与右子树的高度之差的绝对值不能超过1。左子树与右子树的高度之差又被称为平衡因子。
4.1 AVL树的基本结构和函数
struct Node{
int v, height; //额外需要一个height成员来记录当前子树高度
Node* lchild;
Node* rchild;
};
//新建结点
Node* newNode(int v){
Node* temp = new Node;
temp->v = v;
temp->height = 1;
temp->lchild = temp->rchild = NULL;
return temp;
}
//获取结点所在子树的高度
int getHeight(Node* root){
if(root == NULL) return 0;
else return root->height;
}
//计算平衡因子
int getBF(Node* root){
if(root == NULL) return 0;
return getHeight(root->lchild) - getHeight(root->rchild);
}
//更新height
void updateHeight(Node* root){
if(root == NULL) return;
root->height = max(getHeight(root->lchild), getHeight(root->rchild)) + 1;
}
4.2 AVL树的基本操作
//查找操作
void search(Node* root, int x){
if(root == NULL){
printf("没找到");
return;
}
if(root->v == x){
printf("找到啦!");
return;
}
else if(root->v > x) search(root->lchild, x);
else search(root->rchild, x);
}
//左旋
void L(Node* &root){
Node* temp = root->rchild;
root->rchild = temp->lchild;
temp->lchild = root;
updateHeight(root);
updateHeight(temp);
root = temp;
}
//右旋
void R(Node* &root){
Node* temp = root->lchild;
root->lchild = temp->rchild;
temp->rchild = root;
updateHeight(root);
updateHeight(temp);
root = temp;
}
//插入操作,提前写好左旋右旋代码
void insert(Node* &root, int x){
if(root == NULL){
root = newNode(x);
return;
}
if(v < root->v){
insert(root->lchild, x);
updateHeight(root);
if(getBF(root) == 2){
if(getBF(root->lchild) == 1){
R(root);
}
else if(getBF(root->lchild) == -1){
L(root->lchild);
R(root);
}
}
}
else{
insert(root->rchild, x);
updateHeight(root);
if(getBF(root) == -2){
if(getBF(root->rchild) == -1){
L(root);
}
else if(getBF(root->rchild) == 1){
R(root->rchild);
L(root);
}
}
}
}
AVL树删除节点的过程是,先找到该节点,然后进行删除。由于删除节点的位置不同,导致删除后节点进行移动的方式不同。删除节点的位置分为以下4类:
1.删除叶子结点。操作:直接删除,然后依次向上调整为AVL树。
2.删除非叶子节点,该节点只有左孩子。操作:该节点的值替换为左孩子节点的值,然后删除左孩子节点。【左孩子节点为叶子结点,所以删除左孩子节点的情况为第1种情况。】【为什么左孩子节点为叶子节点,因为删除节点前,该树是AVL树,由AVL树的定义知,每个节点的左右子树的高度差的绝对值<=1,由于该节点只有左孩子,没有右孩子,如果左孩子还有子节点,那么将不满足每个节点的左右子树的高度差的绝对值<=1,所以左孩子节点为叶子结点】
3.删除非叶子节点,该节点只有右孩子。操作:该节点的值替换为右孩子节点的值,然后删除右孩子节点。【右孩子节点为叶子结点,所以删除右孩子节点的情况为第1种情况。】【为什么右孩子节点为叶子节点?答案和第二种情况一样】
4.删除非叶子节点,该节点既有左孩子,又有右孩子。操作:该节点的值替换为该节点的前驱节点(或者后继节点),然后删除前驱节点(或者后继节点)。【前驱结点:在中序遍历中,一个节点的前驱结点,先找到该节点的左孩子节点,再找左孩子节点的最后一个右孩子节点。向左走一步,然后向右走到头。最后一个右孩子节点即为前驱节点】【后继节点:在中序遍历中,一个节点的后继结点,先找到该节点的右孩子节点,再找右孩子节点的最后一个左孩子节点。向右走一步,然后向左走到头。最后一个左孩子节点即为前驱节点】
总结:对于非叶子节点的删除,最终都将转化为对叶子节点的删除。
5 堆
堆是一棵完全二叉树,树中每个结点的值都不小于(或不大于)其左右孩子结点的值。堆一般用于优先队列的实现,优先队列默认大顶堆。
5.1 堆的定义与基本操作
堆的定义:
const int MAXN = 1000;
int heap[MAXN], n = 10; //n为元素个数
建堆过程为对所有的非叶子结点进行向下调整,完全二叉树中,假设元素下标为1到n,那么非叶子节点的下标为[1, n/2(下取整)],建堆的时间复杂度为O(n)。
//对heap数组在[low, high]范围内向下调整
void downAdjust(int low, int high){
int i = low, j = i * 2;
while(j <= high){
if(j+1 <= high && heap[j+1] > heap[j]){
j = j + 1;
}
if(heap[j] > heap[i]){
swap(heap[j], heap[i]);
i = j;
j = i * 2;
}
else{
break;
}
}
}
void createHeap(){
for(int i = n/2; i>=1; i--){
downAdjust(i, n);
}
}
删除堆顶元素的时间复杂度为为O(logN)
void deleteTop(){
heap[1] = heap[n--];
downAdjust(1,n);
}
但是如果要向堆里添加元素,就要用到向上调整,添加的元素到数组的末尾,再依次比较添加的元素与其父亲结点的大小关系,时间复杂度为为O(logN)。
void upAdjust(int low, int high){
int i = high, j = i/2;
while(j >= low){
if(heap[j] < heap[i]){
swap(heap[j], heap[i]);
i = j;
j = i/2;
}
else{
break;
}
}
}
void insert(int x){
heap[++n] = x;
upAdjust(1, n);
}
5.2 堆排序
每次把堆顶的元素与最后的元素交换,然后进行向下调整。
void heapSort(){
createHeap();
for(int i=n; i>1; i--){
swap(heap[1], heap[i]);
downAdjust(1,i-1);
}
}
6 哈夫曼树
6.1 最小带权路径长度
叶子节点的带权路径长度为节点的权值乘以其路径长度。
树的带权路径长度(WPL,Weighted Path Length of Tree):所有叶子节点的带权路径长度之和。
对同一组叶子节点来说,哈夫曼树不唯一,但最小带权路径长度一定是唯一的。
合并果子问题的代码:已知n个数,寻找一棵树,使得树的所有叶子结点的权值恰好为这n个数,并且使得这棵树的带权路径长度最小。
#include<bits/stdcpp.h>
using namespace std;
typedef long long LL;
priority_queue<LL, vector<LL>, greater<LL> > q;
int n;
int main(){
LL temp, x, y;
cin >> n;
for(int i=0; i<n; i++){
scanf("%lld",&temp);
q.push(temp);
}
while(q.size() > 1){
x = q.top();
q.pop();
y = q.top();
q.pop();
q.push(x+y);
}
printf("%lld\n",q.top());
return 0;
}
6.2 哈夫曼编码
如果把字符的出现频数作为各自叶子结点的权值,那么字符串编码成01串后的长度实际上就是这颗树的带权路径长度。
#include <cstdio>
#include <queue>
using namespace std;
const int MAXN=2048;
struct Node{
char c;
double weight;
Node* left;
Node* right;
Node() {
left=NULL, right=NULL;
}
};
struct cmp{
bool operator () (Node* a, Node* b){
return a->weight > b->weight;
}
};
priority_queue<Node*, vector<Node*>, cmp> q;
int code[MAXN], cur=0;
void DFS(Node* h) {
if(h->left==NULL && h->right==NULL) {
printf("%c -> ", h->c);
for(int i=0;i<cur;i++)
printf("%d", code[i]);
printf("\n");
return;
}
code[cur++] = 0;
DFS(h->left);
cur--;
code[cur++] = 1;
DFS(h->right);
cur--;
return;
}
int main() {
double w;
int n;
char ch;
scanf("%d",&n);
getchar();
for(int i=0; i<n; i++){
scanf("%c %lf",&ch,&w);
if(i < n-1) getchar();
Node* h = new Node();
h->weight = w;
h->c = ch;
q.push(h);
}
while(q.size()>1) {
Node* h1 = q.top();
q.pop();
Node* h2 = q.top();
q.pop();
Node* h = new Node();
h->left = h1;
h->right = h2;
h->weight = h1->weight + h2->weight;
q.push(h);
}
Node* root = q.top();
DFS(root);
return 0;
}
/*
输入:
5
A 0.1
B 0.15
C 0.2
D 0.25
E 0.3
输出:
C -> 00
D -> 01
A -> 100
B -> 101
E -> 11
*/