注意:不是二叉排序树,只是普通的二叉树。
相信二叉树的递归遍历对于很多人来说是很容易的,但这里要复习下非递归的实现。
前序和中序的非递归遍历相对容易一些,前序是从根到左子树不停的访问然后入栈,等左子树遍历到空时,出栈,再指向它的右子树,按照之前的规律入栈,一直执行。。。而中序略微变化一下,在入栈时先不访问,出栈时对对应结点进行访问。
后序访问也参考前两种解法,但注意根是最后访问的,所以如果第一次出栈,先访问它的右结点,再进栈,第二次出栈时直接访问结点本身,不再入栈。代码如下:
#include<iostream>
#include <stdio.h>
#include<stack>
#include <queue>
using namespace std;
//复习:非递归的二叉树前中后序遍历
struct BSTree{
int value;
BSTree* left;
BSTree* right;
};
struct Node{
BSTree* tree;
bool first;
};
BSTree* CreateTree(){
BSTree *t;
int x;
cin>>x;
if(x == 0)
t = NULL;
else{
t = new BSTree();
t->value =x;
printf("输入%d点的左孩子\n",x);
t->left = CreateTree();
printf("输入%d点的右孩子\n",x);
t->right= CreateTree();
}
return t;
}
void printfTree(BSTree * root){
if(root == NULL)
return;
queue<BSTree *> Queue;
BSTree *temp;
Queue.push(root);
while(!Queue.empty()){
temp = Queue.front();
Queue.pop();
cout<<" "<<temp->value;
if(temp->left)
Queue.push(temp->left);
if(temp->right)
Queue.push(temp->right);
}
cout<<endl;
}
void preorder(BSTree *root){
if(root == NULL)
return;
stack<BSTree *> s;
while(root || !s.empty()){
while(root){
cout<<" "<<root->value;
s.push(root);
root = root->left;
}
if(!s.empty()){
root = s.top();
s.pop();
root = root->right;
}
}
}
void midorder(BSTree *root){
if(root == NULL)
return;
stack<BSTree *> s;
while(root || !s.empty()){
while(root){
s.push(root);
root = root->left;
}
if(!s.empty()){
root = s.top();
s.pop();
cout<<" "<<root->value;
root = root->right;
}
}
}
void postorder(BSTree *root){
if(root == NULL)
return;
stack<BSTree *> s;
bool tag[20];
while(root || !s.empty()){
while(root){
tag[root->value] = true;
s.push(root);
root = root->left;
}
if(!s.empty()){
root = s.top();
s.pop();
if(tag[root->value] == true){
tag[root->value] = false;
s.push(root);
root = root->right;
}
else if(tag[root->value] == false){
cout<<" "<<root->value;
root = NULL;
}
}
}
}
int main(){
BSTree *root = CreateTree();
cout<<"树的层次遍历序列为:"<<endl;
printfTree(root);
cout<<"前序的遍历序列为:"<<endl;
preorder(root);
cout<<endl;
cout<<"中序的遍历序列为:"<<endl;
midorder(root);
cout<<endl;
cout<<"后序的遍历序列为:"<<endl;
postorder(root);
cout<<endl;
system("PAUSE");
return 0;
}
建立的树图示如下:
测试结果如下图: