包含了二叉树的递归建立、前中后序遍历的递归和非递归实现以及层序遍历的非递归实现。
#include<iostream>
#include<queue>
#include<stack>
using namespace std;
typedef struct TreeNode{
char data;
TreeNode *lchild,*rchild;
}TreeNode;
//输入二叉树的前序遍历序列来构建二叉树,#号代表结点为空
TreeNode* createBinaryTree(TreeNode* root){
char ch;
cin>>ch;
if(ch=='#')
root=NULL;
else{
root=new TreeNode;
root->data=ch;
root->lchild=createBinaryTree(root->lchild);
root->rchild=createBinaryTree(root->rchild);
}
return root;
}
//二叉树前序遍历的递归实现
void preOrder(TreeNode* root){
if(!root)
return;
else{
cout<<root->data<<" ";
preOrder(root->lchild);
preOrder(root->rchild);
}
}
//二叉树中序遍历的递归实现
void inOrder(TreeNode* root){
if(!root)
return;
else{
inOrder(root->lchild);
cout<<root->data<<" ";
inOrder(root->rchild);
}
}
//二叉树后序遍历的递归实现
void postOrder(TreeNode* root){
if(!root)
return;
else{
postOrder(root->lchild);
postOrder(root->rchild);
cout<<root->data<<" ";
}
}
//二叉树层序遍历的非递归实现(采用队列)
void levelOrder(TreeNode* root){
if(!root)
return;
queue<TreeNode*> que;
que.push(root);
while(!que.empty()){
TreeNode *cur=que.front();
que.pop();
cout<<cur->data<<" ";
if(cur->lchild)
que.push(cur->lchild);
if(cur->rchild)
que.push(cur->rchild);
}
}
//二叉树前序遍历的非递归实现。(采用函数重载的机制,增加一个bool型参数作为区分)
//中序遍历和后序遍历同前序遍历
void preOrder(TreeNode* root,bool isRecur){
if(!root)
return;
stack<TreeNode*> s;
TreeNode* cur=root;
while(cur||!s.empty()){
//迭代访问结点的左孩子,并入栈
while(cur){
cout<<cur->data<<" ";
s.push(cur);
cur=cur->lchild;
}
if(!s.empty()){
cur=s.top();
s.pop();
cur=cur->rchild;
}
}
}
void inOrder(TreeNode* root,bool isRecur){
if(!root)
return;
TreeNode* cur=root;
stack<TreeNode*> s;
while(cur||!s.empty()){
while(cur){
s.push(cur);
cur=cur->lchild;
}
//中序遍历在左结点为空时输出根节点
if(!s.empty()){
cur=s.top();
s.pop();
cout<<cur->data<<" ";
cur=cur->rchild;
}
}
}
//后序遍历:遍历顺序仍旧是先左后右。因为是后序遍历,如果当前栈顶元素有右节点,则不pop,cur=top->right,
//然后把栈顶元素的右指针置为nullptr
void postOrder(TreeNode* root,bool isRecur){
if(!root)
return;
TreeNode *cur=root;
stack<TreeNode*> s;
while(cur||!s.empty()){
if(cur){
s.push(cur);
cur=cur->lchild;
}
else{
TreeNode* top=s.top();
if(!top->rchild){
s.pop();
cout<<top->data<<" ";
continue;
}
cur=top->rchild;
top->rchild=nullptr;
}
}
}
int main()
{ TreeNode *root=NULL;
root=createBinaryTree(root);
cout<<"The binary tree has been created successfully!"<<endl;
cout<<"PreOrder is:";
preOrder(root);
cout<<endl;
cout<<"InOrder is:";
inOrder(root);
cout<<endl;
cout<<"PostOrder is:";
postOrder(root);
cout<<endl;
cout<<"LevelOrder is:";
levelOrder(root);
cout<<endl;
cout<<"No-Recur PreOrder is:";
preOrder(root,0);
cout<<endl;
cout<<"No-Recur InOrder is:";
inOrder(root,0);
cout<<endl;
cout<<"No-Recur PostOrder is:";
postOrder(root,0);
cout<<endl;
return 0;
}