#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
typedef struct treeNode
{
int data;
struct treeNode* rChild;
struct treeNode* lChild;
}tree, *BinTree;
typedef struct
{
tree Tree[30];
int top;
}stack;
int creatTree(BinTree& pNode)
{
int ch;
scanf("%d", &ch);
if (ch == 0)
{
pNode = NULL;
}
else
{
pNode = (BinTree)malloc(sizeof(tree));
pNode->data = ch;
creatTree(pNode->lChild);
creatTree(pNode->rChild);
return 0;
}
}
void initStack(stack& s)
{
s.top = 0;
}
void push(stack& p, BinTree pNode)
{
p.Tree[p.top] = *pNode;
p.top++;
}
BinTree pop(stack& p)
{
BinTree temp = &p.Tree[p.top];
p.top--;
return temp;
}
bool isEmpty(stack p)
{
if (p.top == 0)
{
return true;
}
else
{
return false;
}
}
void inOrderTravelTree(BinTree p1,stack s)
{
initStack(s);
while (p1 || !isEmpty(s))
{
while (p1 != NULL)
{
push(s, p1);
p1 = p1->lChild;
}
if (!isEmpty(s))
{
printf("%d", pop(s)->data);
p1 = pop(s)->rChild;
}
}
}
int main()
{
stack s;
BinTree pHead=NULL;
creatTree(pHead);
inOrderTravelTree(pHead,s);
return 0;
}
(借助栈)二叉树中序非递归遍历
最新推荐文章于 2021-09-13 16:05:10 发布