题目描述
给定一颗二叉树的逻辑结构如下图,(先序遍历的结果,空树用字符‘0’表示,例如AB0C00D00),建立该二叉树的二叉链式存储结构。
编写程序输出该树的所有叶子结点和它们的父亲结点
输入
第一行输入一个整数t,表示有t个二叉树
第二行起,按照题目表示的输入方法,输入每个二叉树的先序遍历,连续输入t行
输出
第一行按先序遍历,输出第1个示例的叶子节点
第二行输出第1个示例中与叶子相对应的父亲节点
以此类推输出其它示例的结果
输入输出样例
输入样例1 <-复制
3
AB0C00D00
AB00C00
ABCD0000EF000
输出样例1
C D
B A
B C
A A
D F
C E
AC代码
#include <iostream>
#include <string>
#include<queue>
using namespace std;
class BiTreeNode {
public:
char data; //数据域
BiTreeNode *leftChild, *rightChild, *parent;
BiTreeNode() :leftChild(NULL), rightChild(NULL) {}
~BiTreeNode() {}
};
class BiTree {
private:
BiTreeNode *root; //根结点指针
string sTree; //建树字符串
int pos; //标识建树字符串的当前字符位置
int yezi;
BiTreeNode * CreateTree();//建树私有函数
void PreOrder(BiTreeNode *t); //先序遍历实现
queue <char>ye, fu;
public:
BiTree() :root(NULL) {};
void Create(string vArray); //建树公有接口,参数是特定的先序遍历字符串
void PreOrder(); //先序遍历公有接口
void show()
{
while (!ye.empty())
{
cout << ye.front();
ye.pop();
if (!ye.empty())
cout << " ";
else
cout << " " << endl;
}
while (!fu.empty())
{
cout << fu.front();
fu.pop();
if (!fu.empty())
cout << " ";
else
cout << " " << endl;
}
}
};
//二叉树公有接口的实现
void BiTree::Create(string vArray)
{
pos = 0;
yezi = 0;
sTree.assign(vArray); //把参数保存到内部字符串
root = CreateTree(); //建树成功后root指向根结点
}
void BiTree::PreOrder()
{
PreOrder(root);
}
BiTreeNode* BiTree::CreateTree()//建树私有函数
{
BiTreeNode *T;
char ch = sTree[pos++];
if (ch == '0')
T = NULL;
else
{
T = new BiTreeNode();
T->data = ch;
T->leftChild = CreateTree();
if(T->leftChild!=NULL)
T->leftChild->parent = T;
T->rightChild = CreateTree();
if (T->rightChild != NULL)
T->rightChild->parent = T;
}
return T;
}
void BiTree::PreOrder(BiTreeNode* t) //先序遍历实现
{
if (t == NULL)
return ;
if (t->leftChild == NULL&&t->rightChild == NULL)
{
ye.push(t->data);
fu.push(t->parent->data);
return;
}
PreOrder(t->leftChild);
PreOrder(t->rightChild);
}
//主函数
int main()
{
int t;
string vArray;
cin >> t;
while (t--)
{
cin >> vArray;
BiTree myTree;
myTree.Create(vArray);
myTree.PreOrder();
myTree.show();
}
return 0;
}
(by 归忆)