#include "stdafx.h"
#include <stack>
struct bitreeNode
{
int value;
bitreeNode * left;
bitreeNode * right;
};
//先序
int bitreePreOrder(bitreeNode * root)
{
stack <bitreeNode *> st;
bitreeNode * node = root;
do
{
while(root)
{
printf("%d,", root->value);
st.push(root);
root = root->left;
}
if(st.size() == 0)
break;
root = (bitreeNode *)st.top();
st.pop();
root = root->right;
}
while(1);
return 0;
}
//中序
int bitreeInOrder(bitreeNode * root)
{
stack <bitreeNode *> st;
bitreeNode * node = root;
do
{
while(root)
{
st.push(root);
root = root->left;
}
if(st.size() == 0)
break;
root = (bitreeNode *)st.top();
st.pop();
printf("%d", root->value);
root = root->right;
}
while(1);
return 0;
}
//后序
struct BadIdea{
bitreeNode * node;
bool first;
};
int bitreePostOrder(bitreeNode * root)
{
stack <BadIdea> st;
BadIdea idea;
BadIdea node;
do
{
while(root)
{
idea.node = root;
idea.first = true;
st.push(idea);
root = root->left;
}
if(st.size() == 0)
break;
node = (BadIdea)st.top();
st.pop();
if(node.first)
{
node.first = false;
root = node.node->right;
st.push(node);
}
else
{
printf("%d", node.node->value);
root = NULL;
}
}
while(1);
return 0;
}
#define BITREE_SIZE 10
int _tmain(int argc, _TCHAR* argv[])
{
bitreeNode * root = (bitreeNode *)malloc(sizeof(bitreeNode) * BITREE_SIZE);
for(int i=0; i<BITREE_SIZE; i++)
{
root[i].value = i;
if((i * 2 +1) < BITREE_SIZE)
root[i].left = &(root[i*2+1]);
else
root[i].left = NULL;
if((i * 2 + 2) < BITREE_SIZE)
root[i].right = &(root[i*2 + 2]);
else
root[i].right = NULL;
}
bitreePreOrder(root);
bitreeInOrder(root);
bitreePostOrder(root);
return 0;
}
二叉树非递归先序遍历、中序遍历、后序遍历
最新推荐文章于 2023-11-09 21:20:04 发布