D.牛牛与二叉树的数组存储
题目链接-D.牛牛与二叉树的数组存储
上图是一颗满二叉树,对于每个节点i,i2是它的左子树,i2+1是它的右子树,i/2则是它的父亲节点。当然了,当树不为满二叉树的时候其实也能储存
上图是树不为满二叉树的情况,我们先用一些虚点将其补充成一颗满二叉树。
根节点还是被储存到数组的第1个位置。
然后对于下标为i的节点,他的左孩子的下标为i* 2,它的右孩子的下标为i*2+1,它的父亲节点的下标为i/2。
给你一个长度为n的数组,该数组储存了一颗二叉树,数组中仅含有-1和正整数,且整个数组中的正整数是从1到树尺寸连续的,不会出现如1,2,3,5,6,这种缺少4断掉的情况。
请你告诉我树的尺寸和根节点,并按照顺序打印每个节点的父亲节点、左孩子、右孩子分别是谁?
输入
7
1 2 3 4 5 6 7
输出
The size of the tree is 7
Node 1 is the root node of the tree
The father of node 1 is -1, the left child is 2, and the right child is 3
The father of node 2 is 1, the left child is 4, and the right child is 5
The father of node 3 is 1, the left child is 6, and the right child is 7
The father of node 4 is 2, the left child is -1, and the right child is -1
The father of node 5 is 2, the left child is -1, and the right child is -1
The father of node 6 is 3, the left child is -1, and the right child is -1
The father of node 7 is 3, the left child is -1, and the right child is -1
输入
7
3 -1 2 -1 -1 1 4
输出
The size of the tree is 4
Node 3 is the root node of the tree
The father of node 1 is 2, the left child is -1, and the right child is -1
The father of node 2 is 3, the left child is 1, and the right child is 4
The father of node 3 is -1, the left child is -1, and the right child is 2
The father of node 4 is 2, the left child is -1, and the right child is -1
解题思路
水题,按题目要求模拟即可
附上代码
#include<bits/stdc++.h>
using namespace std;
const int N=4e6+5;
const int M=1e9+7;
const int INF=0x3f3f3f3f;
const double PI=acos(-1.0);
typedef long long ll;
typedef pair<int,int> PII;
int a[N],pos[N];
int main(){
int n;
cin>>n;
memset(a,-1,sizeof a);
int cnt=0;
for(int i=1;i<=n;i++){
cin>>a[i];
if(a[i]!=-1)
pos[a[i]]=i,cnt++;
}
printf("The size of the tree is %d\n",cnt);
printf("Node %d is the root node of the tree\n",a[1]);
for(int i=1;i<=cnt;i++){
printf("The father of node %d is %d, the left child is %d, and the right child is %d\n",i,a[pos[i]/2],a[pos[i]*2],a[pos[i]*2+1]);
}
return 0;
}