#include<iostream>
#include<queue>
#include<stack>
using namespace std;
typedef struct BTNode
{
int data;
BTNode *lchild,*rchild;
}BTNode,*BTree;
void CreateBTree(BTree &T)
{
int tmp;
cin>>tmp;
if(!tmp)
T=NULL;
else
{
T=new BTNode;
T->data=tmp;
CreateBTree(T->lchild);
CreateBTree(T->rchild);
}
}
void PreOrderTraverse(BTree T)
{
if(T)
{
cout<<T->data<<" ";
PreOrderTraverse(T->lchild);
PreOrderTraverse(T->rchild);
}
}
void BreadthTraverse(BTree T)
{
queue<BTree> BTQueue;
BTQueue.push(T);
while(!BTQueue.empty())
{
BTree bt=BTQueue.front();
cout<<bt->data<<" ";
BTQueue.pop();
if(bt->lchild )
BTQueue.push(bt->lchild);
if(bt->rchild)
BTQueue.push(bt->rchild);
}
cout<<endl;
}
void DepthTraverse(BTree T)
{
stack<BTree> BTStack;
BTStack.push(T);
while(!BTStack.empty())
{
BTree bt=BTStack.top();
cout<<bt->data<<" ";
BTStack.pop();
if(bt->rchild)
BTStack.push(bt->rchild);
if(bt->lchild)
BTStack.push(bt->lchild);
}
cout<<endl;
}
void main()
{
BTree T;
CreateBTree(T);
PreOrderTraverse(T);
cout<<endl;
BreadthTraverse(T);
DepthTraverse(T);
}
二叉树层次遍历和深度遍历
最新推荐文章于 2023-01-11 20:34:14 发布