牛牛与二叉树的数组存储
题号:NC201773
时间限制:C/C++/Rust/Pascal 1秒,其他语言2秒
空间限制:C/C++/Rust/Pascal 256 M,其他语言512 M
64bit IO Format: %lld

题目描述

树是一种重要的非线性数据结构,直观地看,它是数据元素(在树中称为结点)按分支关系组织起来的结构,很象自然界中的树那样。树结构在客观世界中广泛存在,如人类社会的族谱和各种社会组织机构都可用树形象表示。树在计算机领域中也得到广泛应用,如在编译源程序时,可用树表示源源程序的语法结构。又如在数据库系统中,树型结构也是信息的重要组织形式之一。一切具有层次关系的问题都可用树来描述。满二叉树,完全二叉树,排序二叉树。

当一颗二叉树是满二叉树时,可以用如下的规则储存:

  1. 数组0下标不使用 
  2. 节点i的左子节点在位置为(2*i); 
  3. 节点i的右子节点在位置为(2*i+1); 
  4. 节点i的父节点在位置为(i/2);
  5. 根节点被保存到数组下标为1的位置。

 

上图是一颗满二叉树,对于每个节点i,i*2是它的左子树,i*2+1是它的右子树,i/2则是它的父亲节点。
当然了,当树不为满二叉树的时候其实也能储存。


上图是树不为满二叉树的情况,我们先用一些虚点将其补充成一颗满二叉树。

根节点还是被储存到数组的第1个位置。

然后对于下标为i的节点,他的左孩子的下标为i*2,它的右孩子的下标为i*2+1,它的父亲节点的下标为i/2。
 
给你一个长度为n的数组,该数组储存了一颗二叉树,数组中仅含有-1和正整数,且整个数组中的正整数是从1到树尺寸连续的,不会出现如1,2,3,5,6,这种缺少4断掉的情况。

请你告诉我树的尺寸和根节点,并按照顺序打印每个节点的父亲节点、左孩子、右孩子分别是谁?

输入描述:

第一行是一个正整数n,表示数组的大小。

接下来一行n个整数,仅包含-1和正整数,如果输入的是-1,则表示该位置是空节点,反之则为节点编号。输入数据保证整个数组中节点编号是从1到树尺寸连续的。

 

输出描述:

对于每组案例:
首先在第一行输出:"The size of the tree is X",X表示树的尺寸,树的尺寸为二叉树中节点的数目。
接着在第二行输出:"Node X is the root node of the tree",X表示二叉树的根节点,也就是数组下标1的位置所储存的节点。
接下来输出size行,size表示树的尺寸。

每行格式为:"The father of node I is X, the left child is Y, and the right child is Z",I、X、Y、Z的含义为:第I个节点的父节点为X,它的左孩子为Y,它的右孩子为Z。

如果该节点是根节点,没有父亲节点,则X为-1。

如果该节点没有左孩子,则Y为-1。

如果该节点没有右孩子,则Z为-1。

示例1

输入

复制
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
示例2

输入

复制
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

备注:

温馨提示:为了避免PE,或者肉眼不可见的WA造成不必要的罚时,请使用牛客自带的自测调试功能