题目描述
给出一棵二叉树的特定字符先序遍历结果(空子树用字符'#'表示),构建该二叉树,并输出该二叉树的双亲表示法结果
双亲表示法的数组下标从0开始,根结点必定是在下标0元素,且根结点的双亲下标为-1,左右孩子按下标递增顺序排列,
结点下标是层次遍历顺序。
输入
第一个输入t,表示有t棵二叉树
接着t行,每行输入含特定字符的二叉树先序遍历序列
输出
共输出2t行
每棵二叉树输出两行,第一行输出各个结点的数值,第二行输出各结点的双亲下标
代码
#include <iostream>
#include <string>
using namespace std;
class BiTreeNode {
public:
char data; //数据域
BiTreeNode *leftChild, *rightChild; //左右子树指针
BiTreeNode():leftChild(NULL), rightChild(NULL){}
~BiTreeNode() {}
};
class BiTree {
private:
BiTreeNode *root; //根结点指针
string sTree; //建树字符串
int pos; //标识建树字符串的当前字符位置和当前字符位置
char *parent; //逐层存储结点
int *parentID; //存储结点相应的双亲ID
int size; //有效结点数
BiTreeNode * CreateTree();//建树私有函数
void findChild(BiTreeNode *t);
public:
BiTree():root(NULL) {};
void Create(string vArray); //建树公有接口,参数是特定的先序遍历字符串
void findChild();
void printParentPos();
int findParent(char value);
};
//二叉树公有接口的实现
void BiTree::Create(string vArray)
{ pos=0;
size=0;
sTree.assign(vArray); //把参数保存到内部字符串
root = CreateTree(); //建树成功后root指向根结点
parent=new char[size];
parent[0]=root->data;
parentID=new int[size];
parentID[0]=-1;
pos=0;//归零,用于计算已填充的位置
}
void BiTree::findChild(){
findChild(root);
printParentPos();
}
//私有函数实现
BiTreeNode * BiTree::CreateTree(){
BiTreeNode * root;
if(pos<(int)sTree.length()){
if(sTree[pos]=='#'){
root= NULL;
pos++;
}
else{
root = new BiTreeNode;
root->data = sTree[pos];
pos++;
size++;
root->leftChild = CreateTree();
root->rightChild = CreateTree();
}
}
return root;
}
//找到父结点位置
int BiTree::findParent(char value){
for(int i = 0;i<size;i++){
if(parent[i]==value)
return i;
}
}
void BiTree::findChild(BiTreeNode *t){
if(t!=NULL){
//有子结点则将子结点存储,已填充数目+1
if(t->leftChild){
pos++;
parent[pos]=t->leftChild->data;
parentID[pos]=findParent(t->data);
}
if(t->rightChild){
pos++;
parent[pos]=t->rightChild->data;
parentID[pos]=findParent(t->data);
}
if(t->leftChild)
findChild(t->leftChild);
if(t->rightChild)
findChild(t->rightChild);
}
else
return;
}
void BiTree::printParentPos(){
for(int i = 0;i<size;i++){
cout<<parent[i];
if(i<size-1)
cout<<" ";
}
cout<<endl;
for(int i = 0;i<size;i++){
cout<<parentID[i];
if(i<size-1)
cout<<" ";
else
cout<<endl;
}
}
/*******************************************/
//主函数
int main()
{ int t;
string vArray;
cin>>t;
while(t--)
{ cin>>vArray;
BiTree myTree;
myTree.Create(vArray);
myTree.findChild();
}
return 0;
}