#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<stack>
#include<queue>
using namespace std;
typedef struct TreeNode
{
char Data;
TreeNode* Left;
TreeNode* Right;
}*BinTree;
typedef struct _BinNode
{
BinTree p;
bool isFirst ;
}*BinNode;
void CreateBinTree(BinTree &p)
{
char tmp;
scanf("%c", &tmp);
if (tmp != '#')
{
p = (BinTree)malloc(sizeof(TreeNode));
p->Data = tmp;
CreateBinTree(p->Left);
CreateBinTree(p->Right);
}
else
{
p = NULL;
}
}
void PreOrderTraversal(BinTree T)
{
BinTree BT = T;
stack<BinTree> s;
while (BT || !(s.empty()))
{
while (BT)
{
printf("%c", BT->Data);
s.push(BT);
BT = BT->Left;
}//一直向左面走
if (!s.empty())
{
BT = s.top();
s.pop();
BT = BT->Right;
}
}
}
void InOrderTraversal(BinTree T)
{
BinTree BT = T;
stack<BinTree> s;
while (BT || !(s.empty()))
{
while (BT)
{
s.push(BT);
BT = BT->Left;
}//一直向左面走
if (!s.empty())
{
BT = s.top();
s.pop();
printf("%c", BT->Data);
BT = BT->Right;
}
}
}
void PostOrderTraversal(BinTree T)
{
BinTree BT = T;
stack<BinNode> s;
BinNode node;
while (BT||! (s.empty()))
{
while (BT)
{
BinNode node = (BinNode)malloc(sizeof(_BinNode));
node->p = BT;
node->isFirst = true;
s.push(node);
BT = BT->Left;
}
if (!s.empty())
{
node=s.top();
s.pop();
if (node->isFirst == true)
{
node->isFirst = false;
s.push(node);
BT = node->p->Right;
}
else
{
printf("%c", node->p->Data);
BT = NULL;
}
}
}
}
二叉树的非递归前序、中序、后序遍历
最新推荐文章于 2024-04-13 17:45:29 发布