按完全二叉树的层次遍历给出一棵二叉树的遍历序列(其中用0表示虚结点),要求输出该二叉树的深度及中序遍历该二叉树得到的序列。
输入格式:
首先输入一个整数T,表示测试数据的组数,然后是T组测试数据。每组测试数据首先输入一个正整数n(n≤1000),代表给出的二叉树的结点总数(当然,其中可能包含虚结点)。结点编号均为正整数,且各不相同。 然后输入n个正整数,表示按完全二叉树(即第1层1个结点,第2层2个,第3层4个,第4层有8个……)的层次遍历给出的二叉树遍历序列,如果某个结点不存在(虚结点),则以0代替。
输出格式:
对于每组测试,第一行输出中序遍历二叉树得到的序列(每两个数据之间留一个空格),第二行输出二叉树的深度。
输入样例:
4
1 1
4 1 4 0 2
11 4 2 0 1 5 0 0 0 0 7 6
3 1 0 0
输出样例:
1
1
2 4 1
3
1 2 7 5 6 4
4
1
1
代码长度限制 16 KB 时间限制 400 ms 内存限制 64 MB
解题代码:
#includeusing namespace std; template struct treeNode{ T data; treeNode *L_child,*R_child; }; int nodeData[1005];//存储输入到数字数组 int n; int l; //用来判断是否是第一次输出 template //模板类 class Tree { public: Tree(){ initTree(); }; void initTree(); treeNode * createNode(int nodeNum); void LNR(treeNode *root); int getDep(treeNode *root); treeNode * getRoot(){ return this->root; }; private: treeNode *root; }; template void Tree ::initTree()//初始化根节点 { this->root = new treeNode (); root->L_child=root->R_child=NULL; } template treeNode * Tree ::createNode(int nodeNum)//创建节点 { if(nodeNum>n) return NULL; //如果结点编号超过了总数n,返回NULL if(nodeData[nodeNum]==0) return NULL; //如果该结点的数是0,为空结点,返回NULL treeNode *node = new treeNode (); node->data=nodeData[nodeNum]; node->L_child=createNode(nodeNum*2); node->R_child=createNode(nodeNum*2+1); return node; } template void Tree ::LNR(treeNode *root){ if(root==NULL) return; LNR(root->L_child); if(l==0){ //这里判断是不是第一次输出 ,pta上要判断空格,所以要注意 cout< data; l=1; } else cout<<" "< data; LNR(root->R_child); } template int Tree ::getDep(treeNode *root) { if(root==NULL) return 0; int depL = getDep(root->L_child); int depR = getDep(root->R_child); int max = depL>depR?depL+1:depR+1; return max; } void initNum() { for(int i=0;i<=1002;i++){ nodeData[i]=0; } } int main() { int t; cin>>t; while(t--){ initNum(); cin>>n; l=0; for(int i=1;i<=n;i++){ cin>>nodeData[i]; } Tree *tree = new Tree (); treeNode * root = tree->getRoot(); root = tree->createNode(1); tree->LNR(root); cout< getDep(root)< 解题思路
这里要注意的有两个点
一、因为给的是层次遍历的顺序,而且是一个完全二叉树,根据二叉树的特性可以知道,父节点n,那么左孩子编号就为2n,右孩子的编号就为2n+1,这样子的话,我们一开始,就将要存储的数据输入到数组中,然后通过这个规律进行创建节点,遇到0或者是编号大于n的时候,返回NULL就行,这个结点不存在。
二、PTA上的样例是最末尾不能有空格的,所以中序遍历的时候,不能直接cout<data<<" ",而是要用一个标识符判断一下



