递归遍历
先序遍历
void PreorderTraversal( BinTree BT )
{
if(BT == NULL) return;
printf(" %c", BT->Data);
PreorderTraversal(BT->Left);
PreorderTraversal(BT->Right);
}
中序遍历
void InorderTraversal( BinTree BT )
{
if(BT == NULL) return;
InorderTraversal(BT->Left);
printf(" %c", BT->Data);
InorderTraversal(BT->Right);
}
后序遍历
void PostorderTraversal( BinTree BT )
{
if(BT == NULL) return;
PostorderTraversal(BT->Left);
PostorderTraversal(BT->Right);
printf(" %c", BT->Data);
}
非递归遍历
先序遍历
void PreorderTraversal( BinTree BT )
{
BinTree t;
Stack s = CreateStack();
t = BT;
while (t || !IsEmpty(s))
{
while (t)
{
Push(s, t);
printf(" %c", t->Data);
t = t->Left;
}
t = Pop(s);
t = t->Right;
}
}
中序遍历
void InorderTraversal( BinTree BT )
{
BinTree t;
Stack s = CreateStack();
t = BT;
while (t || !IsEmpty(s))
{
while (t)
{
Push(s, t);
t = t->Left;
}
t = Pop(s);
printf(" %c", t->Data);
t = t->Right;
}
}
后序遍历
void PostorderTraversal( BinTree BT )
{
BinTree t;
Stack s = CreateStack();
t = BT;
while (t || !IsEmpty(s))
{
while (t)
{
Push(s, t);
t->flag = 1;
t = t->Left;
}
t = Pop(s);
if(t->flag == 1)
{
Push(s, t);
t->flag = 2;
t = t->Right;
}
else
{
printf(" %c", t->Data);
t = NULL;
}
}
}
层次遍历
借助数组模拟队列的先进先出
void LevelorderTraversal( BinTree BT )
{
if(BT == NULL) return;
BinTree queue[10000];
int left = 0, right = 0;
queue[right++] = BT;
while (left < right)
{
BinTree t = queue[left++];
printf(" %c", t->Data);
if (t->Left) queue[right++] = t->Left;
if (t->Right) queue[right++] = t->Right;
}
}