#include "stdafx.h"
#include<iostream>
#include<stack>
#include<queue>
using namespace std;
typedef struct BtreeNode
{
int value;
struct BtreeNode *lchild, *rchild;
}BtreeNode;
typedef BtreeNode* Btree;
void CreatTree(Btree &T)
{
char temp2;
int temp;
cin >> temp2;
if (temp2 == '#')
{
T = NULL;
}
else
{
temp = temp2 - '0' + 0;
T = (Btree)malloc(sizeof(BtreeNode));
T->value = temp;
CreatTree(T->lchild);
CreatTree(T->rchild);
}
}
void Preorder(Btree T)
{
if (T)
{
cout << (T->value);
Preorder(T->lchild);
Preorder(T->rchild);
}
}
void Preorder2(Btree T)
{
stack <Btree> stack;
Btree p = T;
while (p != NULL || !stack.empty())
{
while (p != NULL)
{
cout << p->value << " ";
stack.push(p);
p = p->lchild;
}
if (!stack.empty())
{
p = stack.top();
stack.pop();
p = p->rchild;
}
}
}
void Midorder(Btree T)
{
if (T)
{
Midorder(T->lchild);
cout << (T->value);
Midorder(T->rchild);
}
}
void Midorder2(Btree T)
{
stack <Btree> s;
Btree p = T;
while (p != NULL || !s.empty())
{
while (p != NULL)
{
s.push(p);
p = p->lchild;
}
if (!s.empty())
{
p = s.top();
cout << p->value << " ";
s.pop();
p = p->rchild;
}
}
}
void Posorder(Btree T)
{
if (T)
{
Posorder(T->lchild);
Posorder(T->rchild);
cout << (T->value);
}
}
void Posorder2(Btree root) //非递归后序遍历
{
stack <Btree> s;
Btree cur; //当前结点
Btree pre = NULL; //前一次访问的结点
s.push(root);
while (!s.empty())
{
cur = s.top();
if ((cur->lchild == NULL&&cur->rchild == NULL) ||
(pre != NULL && (pre == cur->lchild || pre == cur->rchild)))
{
cout << cur->value << " "; //如果当前结点没有孩子结点或者孩子节点都已被访问过
s.pop();
pre = cur;
}
else
{
if (cur->rchild != NULL)
s.push(cur->rchild);
if (cur->lchild != NULL)
s.push(cur->lchild);
}
}
}
void Floororder(Btree T)
{
queue <Btree> vec;
Btree p = T;
vec.push(p);
while (p != NULL && !vec.empty())
{
p = vec.front();
vec.pop();
cout << p->value;
if (p->lchild)
vec.push(p->lchild);
if (p->rchild)
vec.push(p->rchild);
}
}
int Depth(Btree T)
{
if (T == NULL) return 0;
else
{
int leftdeep = Depth(T->lchild);
int rightdeep = Depth(T->rchild);
return leftdeep > rightdeep ? leftdeep + 1 : rightdeep + 1;
}
}
int main()
{
Btree Tree;
CreatTree(Tree);
//Preorder2(Tree);
//Midorder2(Tree);
//Posorder(Tree);
Floororder(Tree);
Posorder2(Tree);
system("pause");
return 0;
}