第一次写博客,不足之处请大家包涵指出!谢谢!
问题 A: DS二叉树—二叉树构建与遍历(不含框架)
题目描述
给定一颗二叉树的逻辑结构如下图,(先序遍历的结果,空树用字符‘#’表示,例如AB#C##D##),建立该二叉树的二叉链式存储结构,并输出该二叉树的先序遍历、中序遍历和后序遍历结果。
输入
第一行输入一个整数t,表示有t个二叉树
第二行起输入每个二叉树的先序遍历结果,空树用字符‘#’表示,连续输入t行。
输出
输出每个二叉树的先序遍历、中序遍历和后序遍历结果。
样例输入
2
AB#C##D##
AB##C##
样例输出
ABCD
BCAD
CBDA
ABC
BAC
BCA
#include<iostream>
#include<stack>
using namespace std ;
class TreeNode
{
public:
char data ;
TreeNode *leftchild ,*rightchild ;
TreeNode()
{
leftchild = NULL ;
rightchild = NULL ;
data = 0 ;
}
} ;
class Tree
{
public:
TreeNode* root ;
Tree()
{
root = NULL ;
}
void initTree()
{
root = new TreeNode() ;
char ch ;
cin >> ch ;
if (ch!='#')//if the ch is '#' at the beginning, this tree would be empty.
this->createTree(root, ch) ;//2 AB#C##D## AB##C##
else
cout << "EMPTY" << endl ;
}
void createTree(TreeNode *r,char ch)
{
r->data = ch ;
char chleft ,chright ;
cin >> chleft ;
if (chleft!='#')
{
TreeNode* left = new TreeNode() ;
r->leftchild = left ;
createTree(r->leftchild, chleft) ;
}
cin >> chright ;
if (chright!='#')
{
TreeNode* right = new TreeNode() ;
r->rightchild = right ;
createTree(r->rightchild,chright) ;
}
return ;
}
void DLR(TreeNode *r)
{
if (r!=NULL)
{
cout << r->data ;
DLR(r->leftchild) ;
DLR(r->rightchild) ;
}
}
void LDR(TreeNode *r)
{
stack<TreeNode*> mytree ;//initial a stack to achieve the LDR.
TreeNode *temp ;
mytree.push(r) ;//the root node are been pushed into the stack
temp = mytree.top() ;//get the top
while(!mytree.empty())
{
if(temp->leftchild!=NULL)//Loop util the left child is null
{
temp = temp->leftchild ;
mytree.push(temp) ;
}
else //if not, output the data of node, and push the right node into stack(if not null)
{
temp = mytree.top() ;
cout << temp->data ;
mytree.pop() ;
if (temp->rightchild!=NULL)
{
temp = temp->rightchild ;
mytree.push(temp) ;
}
}//After pushing the right child, we begin this loop from left child again
}
}
// void LDR(TreeNode *r)//递归实现中序遍历
// {
// if (r!=NULL)
// {
// LDR(r->leftchild) ;
// cout << r->data ;
// LDR(r->rightchild) ;
// }
// }
void LRD(TreeNode *r)
{
if (r!=NULL)
{
LRD(r->leftchild) ;
LRD(r->rightchild) ;
cout << r->data ;
}
}
};
int main()
{
int t ;
cin >> t ;
while(t--)
{
Tree mytree ;
mytree.initTree() ;
mytree.DLR(mytree.root) ;
cout << endl ;
mytree.LDR(mytree.root) ;
cout << endl ;
mytree.LRD(mytree.root) ;
cout << endl ;
}
return 0 ;
}