参考题目
https://blog.csdn.net/luoyeliufeng/article/details/103592211
首先要明白二叉树的三种遍历方式
- 先序遍历:先访问根节点,再访问左子树,最后访问右子树
- 中序遍历:先访问左子树,再访问根节点,最后访问右子树
- 后序遍历:先访问左子树,再访问右子树,最后访问根节点
一个重要的思想:二叉树中的每一个节点都可以看作是一棵树的根节点
对于非递归遍历,需要借助循环和栈来实现
参考代码:
#include <iostream>
#include <stack>
using namespace std;
template <class T>
class BiNode
{
T data;
BiNode *lChild;
BiNode *rChild;
public:
BiNode():lChild(NULL),rChild(NULL){}
BiNode(T e):lChild(NULL),rChild(NULL),data(e){}
~BiNode(){delete lChild;delete rChild;}
friend class BiTree;
};
class BiTree
{
BiNode<char> *root;
void createTree(BiNode<char> *&t);
void preOrder(BiNode<char> *t);
void midOrder(BiNode<char> *t);
void postOrder(BiNode<char> *t);
public:
BiTree():root(NULL){}
~BiTree(){delete root;}
void createTree();
void preOrder();
void midOrder();
void postOrder();
};
void BiTree::createTree(BiNode<char> *&t) {
char c;
cin>>c;
if (c != '#')
{
t = new BiNode<char>(c);
createTree(t->lChild);
createTree(t->rChild);
}
}
void BiTree::preOrder(BiNode<char> *t) {
// if(t != NULL)
// {
// cout<<t->data;
// preOrder(t->lChild);
// preOrder(t->rChild);
// }
stack<BiNode<char>*> s;
while(t || !s.empty())
{
// TODO 到最左下孩子
while (t)
{
cout<<t->data;
s.push(t);
t=t->lChild;
}
if(!s.empty())
{
t = s.top();
s.pop();
t = t->rChild;
}
}
}
void BiTree::midOrder(BiNode<char> *t) {
// if(t != NULL)
// {
// midOrder(t->lChild);
// cout<<t->data;
// midOrder(t->rChild);
// }
stack<BiNode<char>*> s;
while (t || !s.empty())
{
while (t)
{
s.push(t);
t=t->lChild;
}
if(!s.empty())
{
t = s.top();
s.pop();
cout<<t->data;
t = t->rChild;
}
}
}
void BiTree::postOrder(BiNode<char> *t) {
// if(t != NULL)
// {
// postOrder(t->lChild);
// postOrder(t->rChild);
// cout<< t->data;
// }
BiNode<char> *visited = NULL;
stack<BiNode<char>*> s;
while (t || !s.empty())
{
while (t)
{
s.push(t);
t=t->lChild;
}
if(!s.empty())
{
t = s.top();
s.pop();
if(t->rChild == NULL || t->rChild == visited)
{
cout<<t->data;
visited = t;
t = NULL;
}
else
{
s.push(t);
t = t->rChild;
}
}
}
}
void BiTree::createTree() {
createTree(root);
}
void BiTree::preOrder() {
preOrder(root);
cout<<endl;
}
void BiTree::midOrder() {
midOrder(root);
cout<<endl;
}
void BiTree::postOrder() {
postOrder(root);
cout<<endl;
}
int main() {
int t;
cin>>t;
while (t--)
{
BiTree tree;
tree.createTree();
tree.preOrder();
tree.midOrder();
tree.postOrder();
}
return 0;
}
测试样例
input:
2
ABD##E##CF##G##
output:
ABDECFG
DBEAFCG
DEBFGCA