#include <iostream>
#include <assert.h>
#include <stack>
using namespace std;
typedef struct biTreeNode
{
char data;
struct biTreeNode *lChild;
struct biTreeNode *rChild;
}biTreeNode, *biTreePtr;
void create_preOrder_ptr(biTreePtr* tree)
{
char ch;
ch = getchar();
if ('!' == ch)
return;
else
{
if (ch == '#')
*tree = NULL;
else
{
*tree = (biTreeNode*)malloc(sizeof(biTreeNode));
assert(*tree != NULL);
(*tree)->data = ch;
create_preOrder_ptr(&((*tree)->lChild));
create_preOrder_ptr(&((*tree)->rChild));
}
}
}
void create_preOrder_ref(biTreePtr &tree)
{
char ch;
cin >> ch;
if ('!' == ch)
return;
else
{
if (ch == '#')
tree = NULL;
else
{
tree = (biTreeNode*)malloc(sizeof(biTreeNode));
assert(tree != NULL);
tree->data = ch;
create_preOrder_ref(tree->lChild);
create_preOrder_ref(tree->rChild);
}
}
}
void create_preOrder_val(biTreePtr tree)
{
char ch;
cin >> ch;
if ('!' == ch)
return;
else
{
if (ch == '#')
tree = NULL;
else
{
tree = (biTreeNode*)malloc(sizeof(biTreeNode));
assert(tree != NULL);
tree->data = ch;
create_preOrder_val(tree->lChild);
create_preOrder_val(tree->rChild);
}
}
}
void traverse_preOrder_ref(biTreePtr proot)
{
if (proot)
{
cout << proot->data;
traverse_preOrder_ref(proot->lChild);
traverse_preOrder_ref(proot->rChild);
}
}
void traverse_inOrder_ref(biTreePtr proot)
{
if (proot)
{
traverse_inOrder_ref(proot->lChild);
cout << proot->data;
traverse_inOrder_ref(proot->rChild);
}
}
void traverse_postOrder_ref(biTreePtr proot)
{
if (proot)
{
traverse_postOrder_ref(proot->lChild);
traverse_postOrder_ref(proot->rChild);
cout << proot->data;
}
}
void traverse_preOrder2(biTreeNode *proot)
{
stack<biTreeNode*> stk;
biTreeNode *p = proot;
while(p != nullptr || !stk.empty())
{
while(p != nullptr)
{
cout << p->data << "";
stk.push(p);
p = p->lChild;
}
if(!stk.empty())
{
p = stk.top();
stk.pop();
p = p->rChild;
}
}
}
void traverse_inorder2(biTreeNode *proot)
{
stack<biTreeNode*> stk;
biTreeNode *p = proot;
while(p != nullptr || !stk.empty())
{
while(p != nullptr)
{
stk.push(p);
p = p->lChild;
}
if(!stk.empty())
{
p = stk.top();
cout << p->data << "";
stk.pop();
p = p->rChild;
}
}
}
int main()
{
biTreePtr pTree = NULL;
create_preOrder_ptr(&pTree);
traverse_preOrder_ref(pTree); cout << endl;
traverse_preOrder2(pTree); cout << endl;
traverse_inOrder_ref(pTree); cout << endl;
traverse_inorder2(pTree); cout << endl;
traverse_postOrder_ref(pTree); cout << endl;
return 0;
}