#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <stack>
using namespace std;
/*****************************************************************
*Module Name: 简单二叉树1
*Module Date: 2018.12.11
*Module Auth: 谭路
*Description: 二叉树的生成,结点的遍历,结点的删除操作
*Others: null
*evision History: null
*DateRel VerNotes: null
*XX/XX/XXXXX.X: null
*****************************************************************/
typedef char ElemType;
typedef struct BitNode{
ElemType date;
struct BitNode* lchild, rchild;
}BitNode, *BiTree;
//前序遍历创建二叉树
BiTree CreateTree(BiTree t){
ElemType ch;
scanf("%d", &ch);
if('#' == ch){
t == NULL;
}
else {
t = (BiTree*) malloc(sizeof(BitNode));
if(NULL == t){
fprintf(stderr, "malloc error in CreateTree.
");
}
else {
t->date = ch;
t->lchild = CreateTree(t->lchild);
t->rchild = CreateTree(t->rchild);
}
}
return t;
}
//先序遍历
void PreOrderTraverse(BiTree t){
if(NULL != t){
printf("%c", t->date);
PreOrderTraverse(t->lchild);
PreOrderTraverse(t->rchild);
}
}
//后序遍历非递归实现,可以将栈改为自己编写的数据结构
bool NoPostOrderTraverse(BiTree t){
stack<BiTree> s;
if(!s.empty()){
while(!s.top()){
s.pop();
}
}
BiTree cur; //当前结点
BiTree pre = NULL; //前一次访问的结点
BiTree tmp; //临时结点
if(NULL == t){
fprintf(stderr, "the tree is null.
");
return false;
}
s.push(t);
while(!s.empty()){
cur = s.top();
if((cur->lchild == NULL && cur->rchild == NULL) ||
(pre != NULL && (pre == cur->lchild || pre == cur->rchild)))
{
printf("%c", cur->date);
s.pop();
pre = cur;
}
else {
if(cur->rchild != NULL){
s.push(cur->rchild);
}
if(cur->lchild != NULL){
s.push(cur->lchild);
}
}
}
return true;
}
//前序遍历查找需要的数据
boolean PreOrderTraverse(BiTree t, ElemType date, BitNode *p){
if(NUll == t){
if(t->date == date){
p = t;
return true;
}
else {
PreOrderTraverse(t->lchild, date, p);
PreOrderTraverse(t->rchild, date, p);
}
}
}
// 2018-12-12