上代码,不废话。
/* 二叉树先序遍历 */
void PreTraverTree(PBinTree tree)
{
if(tree == NULL) {
perror("root is null.");
return;
}
PStack nodeStack = CreateStack();
PBinTree temp = tree;
while(!StackIsEmpty(nodeStack) || temp != NULL) {
if(temp!=NULL) {
printf("%c ", temp->nodeValue);
PushIntoStack(nodeStack, temp);
temp = temp->leftChild;
} else {
temp = GetTop(nodeStack);
PopFromStack(nodeStack);
temp = temp->rightChild;
}
}
printf("\n");
DestroyStack(nodeStack);
}
/* 二叉树后序遍历 */
void PostTraverTree(PBinTree tree)
{
if(tree == NULL) {
perror("root is null.");
return;
}
PStack nodeStack = CreateStack();
PBinTree temp = tree;
while(!StackIsEmpty(nodeStack) || temp != NULL) {
while(temp!=NULL) {
PushIntoStack(nodeStack, temp);
temp = temp->leftChild;
}
temp = GetTop(nodeStack);
PopFromStack(nodeStack);
printf("%c ", temp->nodeValue);
if(!StackIsEmpty(nodeStack) && temp == GetTop(nodeStack)->leftChild) {
temp = GetTop(nodeStack)->rightChild;
} else {
temp = NULL;
}
}
printf("\n");
DestroyStack(nodeStack);
}
/* 二叉树中序遍历 */
void InTraverTree(PBinTree tree)
{
if(tree == NULL) {
perror("root is null.");
return;
}
PStack nodeStack = CreateStack();
PBinTree temp = tree;
while(!StackIsEmpty(nodeStack) || temp != NULL) {
while(temp != NULL) {
PushIntoStack(nodeStack, temp);
temp = temp->leftChild;
}
temp = GetTop(nodeStack);
PopFromStack(nodeStack);
printf("%c ", temp->nodeValue);
if(temp->rightChild != NULL) {
temp = temp->rightChild;
}
else {
temp = NULL;
}
}
printf("\n");
DestroyStack(nodeStack);
}