题目描述
给定一颗二叉树的逻辑结构,(先序遍历的结果,空树用字符‘0’表示,例如AB0C00D00),建立该二叉树的二叉链式存储结构。
编写程序输出该树的所有叶子结点和它们的父亲结点
输入
第一行输入一个整数t,表示有t个二叉树
第二行起,按照题目表示的输入方法,输入每个二叉树的先序遍历,连续输入t行
输出
第一行按先序遍历,输出第1个示例的叶子节点
第二行输出第1个示例中与叶子相对应的父亲节点
以此类推输出其它示例的结果
样例输入
3
AB0C00D00
AB00C00
ABCD0000EF000样例输出
C D
B A
B C
A A
D F
C E
#include <iostream>
#include <queue>
using namespace std;
//二叉树的链式存储结构
class Binary_tree_node
{
private:
char data; //数据域
Binary_tree_node *LeftChild; //左孩子
Binary_tree_node *RightChild; //右孩子
public:
Binary_tree_node() : LeftChild(NULL), RightChild(NULL) {}
~Binary_tree_node()
{
delete LeftChild;
delete RightChild;
}
friend class Binary_tree;
};
class Binary_tree
{
private:
Binary_tree_node *Root; //根结点
int pos;
string str;
Binary_tree_node *CreateBinary_tree() //先序建立二叉树
{
Binary_tree_node *t;
char ch;
ch = str[pos++];
if (ch == '0') //结点为空
{
t = NULL;
}
else //结点不为空
{
t = new Binary_tree_node();
t->data = ch;
t->LeftChild = CreateBinary_tree();
t->RightChild = CreateBinary_tree();
}
return t; //返回根结点
}
void getLeaf(Binary_tree_node *t, char ch) //获取叶子结点和父亲结点
{ //传入父节点跟父节点对应的值
if (t != NULL)
{
if (!t->LeftChild && !t->RightChild) //若该结点左右孩子为空,则为叶子结点
{
cout << t->data << " ";
Q.push(ch);
leaf++;
}
getLeaf(t->LeftChild, t->data);
getLeaf(t->RightChild, t->data);
}
}
public:
int leaf;
queue<char> Q; //创建队列Q用于存储叶子结点相对应的父亲节点
Binary_tree() {}
~Binary_tree() {}
void CreateTree(string tree_array)
{
pos = 0;
leaf = 0;
str=tree_array;
Root = CreateBinary_tree();
}
void getLeaf()
{
getLeaf(Root, Root->data);
}
};
int main()
{
int t;
cin >> t;
while (t--)
{
string str;
Binary_tree Bt;
cin >> str;
Bt.CreateTree(str);
Bt.getLeaf(); //输出叶子结点
cout << endl;
while (!Bt.Q.empty()) //输出叶子相对应的父亲节点
{
cout << Bt.Q.front() << " ";
Bt.Q.pop();
}
cout << endl;
}
return 0;
}