题意:
当一颗二叉树是满二叉树时,可以用如下的规则储存:
1.数组0下标不使用
2.节点i的左子节点在位置为(2i);
3.节点i的右子节点在位置为(2i+1);
4.节点i的父节点在位置为(i/2);
5.根节点被保存到数组下标为1的位置。
如果数不为满二叉树,把空的位置补成-1
然后询问一下,每个节点的父亲节点、左孩子、右孩子
分析:
直接按题意求出,然后输出即可,数组开2倍
代码:
#include <iostream>
#include <stdio.h>
#include <algorithm>
#include <string.h>
#include <vector>
#include <math.h>
#include <map>
#include <queue>
#include <set>
#define Pll make_pair
using namespace std;
typedef long long ll;
const int MAXN=4e5+50;
const int inf=0x3f3f3f3f;
const int mod=1e9+7;
const int phi=1e9+6;
char ch[MAXN];
int a[MAXN];
int fa[MAXN];
int l[MAXN];
int r[MAXN];
int main()
{
int n;
scanf("%d",&n);
int ans=0;
for(int i=0;i<=MAXN;i++)a[i]=fa[i]=l[i]=r[i]=-1;
for(int i=1;i<=n;i++){
scanf("%d",&a[i]);
if(a[i]!=-1)ans++;
}
printf("The size of the tree is %d\n",ans);
printf("Node %d is the root node of the tree\n",a[1]);
for(int i=1;i<=n;i++){
if(a[i]!=-1){
fa[a[i]]=a[i/2];
l[a[i]]=a[i*2];
r[a[i]]=a[i*2+1];
}
}
for(int i=1;i<=ans;i++){
printf("The father of node %d is %d, the left child is %d, and the right child is %d\n",i,fa[i],l[i],r[i]);
}
return 0;
}
/*
*/