二叉树的层序,先序,后序,中序遍历。自己练习加了queue头文件,不能交pta
思路是,在树不为空的条件下,将第一个元素加入队列中,输出的时候从q第一个元素开始,若第一个元素左子树右子树不为空,继续加入队列中,知道队列位空。
不用队列也可以实现。
#include <stdio.h>
#include <stdlib.h>
#include<iostream>
#include<bits/stdc++.h>
#include<queue>
using namespace std;
typedef char ElementType;
typedef struct TNode *Position;
typedef Position BinTree;
struct TNode{
ElementType Data;
BinTree Left;
BinTree Right;
};
BinTree CreatBinTree()
{
BinTree BT;
ElementType ch;
cin>>ch;
if(ch=='#')
{
BT=NULL;
}
else
{
BT=new TNode;
BT->Data=ch;
BT->Left=CreatBinTree();
BT->Right=CreatBinTree();
}
return BT;
}
void InorderTraversal( BinTree BT )
{
if(BT)
{
InorderTraversal(BT->Left);
cout<<BT->Data<<" ";
InorderTraversal(BT->Right);
}
}
void PreorderTraversal( BinTree BT )
{
if(BT)
{
cout<<BT->Data<<" ";
InorderTraversal(BT->Left);
InorderTraversal(BT->Right);
}
}
void PostorderTraversal( BinTree BT )
{
if(BT)
{
InorderTraversal(BT->Left);
InorderTraversal(BT->Right);
cout<<BT->Data<<" ";
}
}
void LevelorderTraversal( BinTree BT )
{
queue<BinTree> q;
BinTree p;
if(BT)
{
q.push(BT);
while(!q.empty())
{
p=q.front();
q.pop();
cout<<p->Data<<" ";
if(p->Left)
q.push(p->Left);
if(p->Right)
q.push(p->Right);
}
}
}
int main()
{
BinTree BT = CreatBinTree();
printf("Inorder:"); InorderTraversal(BT); printf("\n");
printf("Preorder:"); PreorderTraversal(BT); printf("\n");
printf("Postorder:"); PostorderTraversal(BT); printf("\n");
printf("Levelorder:"); LevelorderTraversal(BT); printf("\n");
return 0;
}