DS二叉树——二叉树之父子结点
题目描述
给定一颗二叉树的逻辑结构如下图,(先序遍历的结果,空树用字符‘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<string>
using namespace std;
class BiTreeNode {
public:
char data;
BiTreeNode *LeftChild;
BiTreeNode *RightChild;
BiTreeNode *Parent;
BiTreeNode():LeftChild(NULL),RightChild(NULL),Parent(NULL){}
};
class BiTree {
public:
void CreateTree(string s);
void FindLeaves();
void FindParent();
private:
BiTreeNode *CreateTree();
void FindLeaves(BiTreeNode *t);
void FindParent(BiTreeNode *t);
int len;
int pos;
string strTree;
BiTreeNode *Root;
};
void BiTree::FindParent()
{
FindParent(Root);
}
void BiTree::FindParent(BiTreeNode *t)
{
if(t)
{
if(t->LeftChild)
FindParent(t->LeftChild);
if(t->RightChild)
FindParent(t->RightChild);
if(t->LeftChild == NULL && t->RightChild == NULL)
cout<<t->Parent->data<<" ";
}
}
void BiTree::FindLeaves()
{
FindLeaves(Root);
}
void BiTree::FindLeaves(BiTreeNode *t)
{
if(t)
{
if(t->LeftChild)
FindLeaves(t->LeftChild);
if(t->RightChild)
FindLeaves(t->RightChild);
if(t->LeftChild==NULL&&t->RightChild == NULL)
cout<<t->data<<" ";
}
}
void BiTree::CreateTree(string s)
{
len = 0;
pos = 0;
strTree.assign(s);
Root = CreateTree();
}
BiTreeNode *BiTree::CreateTree()
{
char ch;
ch = strTree[pos++];
BiTreeNode *T;
if(ch == '0')
T = NULL;
else
{
T = new BiTreeNode();
T->data = ch;
T->LeftChild = CreateTree();
if(T->LeftChild)
T->LeftChild->Parent = T;
T->RightChild = CreateTree();
if(T->RightChild)
T->RightChild->Parent = T;
}
return T;
}
int main()
{
int n;
cin>>n;
for(int i=0;i<n;i++)
{
string s;
cin>>s;
BiTree biTree;
biTree.CreateTree(s);
biTree.FindLeaves();
cout<<endl;
biTree.FindParent();
cout<<endl;
}
return 0;
}