typedef struct TreeNode
{
int data;
struct TreeNode *left;
struct TreeNode *right;
int flag; //该标记用于后序非递归遍历
}pTree;
/**************先序递归遍历*****************/
void BT_PreOrder(pTree root)
{
if(root != NULL)
{
Visit(root); //访问节点
BT_PreOrder(root->left);
BT_PreOrder(root->right);
}
}
/**************中序递归遍历*****************/
void BT_MidOrder(pTree root)
{
if(root != NULL)
{
BT_MidOrder(root->left);
Visit(root); //访问节点
BT_MidOrder(root->right);
}
}
/**************后序递归遍历*****************/
void BT_BeOrder(pTree root)
{
if(root != NULL)
{
BT_BeOrder(root->left);
BT_BeOrder(root->right);
Visit(root); //访问节点
}
}
/**************先序非递归遍历*****************/
void BT_PreOrderNoRec(pTree root)
{
InitStack(s);
whlie((root != NULL) || !s.empty())
{
if(root != NULL)
{
Visit(root); //访问节点
s.push(root);
root = root->left;
}
else
{
root = s.pop();
root = root->right;
}
}
}
/**************中序非递归遍历*****************/
void BT_MidOrderNoRec(pTree root)
{
Initstack(s);
whlie((root != NULL) || !s.empty())
{
if(root != NULL)
{
s.push(root);
root = root->left;
}
else
{
root = s.pop();
Visit(root); //访问节点
root = root->right;
}
}
}
/**************后序非递归遍历*****************/
/*二叉树后序遍历的非递归遍历算法中,当当前节点存在右子树的时候需要先遍历右子树
因此要对二叉树的节点定义中添加flag域*/
void BT_BeOrderNoRec(pTree root)
{
InitStack(s);
whlie((root != NULL) || !s.empty())
{
if(root != NULL)
{
s.push(root);
root = root->left;
}
else
{
root = s.top(); //top操作只是获得栈顶的节点,该节点并不出栈
if(root->flag == 1)
{
Visit(root); //访问节点
s.top();
root = NULL;
}
else
{
root->flag = 1;
root = root->right;
}
}
}
}
/**************层次遍历*****************/
void BT_LevelOrder(pTree root)
{
InitQueue q;
if(root == NULL)
return;
q.push(root);
while(!q.empty())
{
root = q.pop();
Visit(root); //访问节点
if(root->left != NULL)
q.push(root->left);
if(root->right != NULL)
q.push(root->right);
}
}