#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <queue>
#include <stack>
#include <iostream>
#include <malloc.h>
#define LEAF -1
using namespace std;
typedef struct BTreeNode{
BTreeNode* lchild;
BTreeNode* rchild;
int value;
}BTreeNode,*Btree;
BTreeNode* createTree(){
BTreeNode* T;
int t;
scanf("%d",&t);
if(t == LEAF){
T = NULL;
}else{
T = (BTreeNode *) malloc(sizeof(BTreeNode));
T->value = t;
T->lchild = createTree();
T->rchild = createTree();
}
return T;
}
void visit(BTreeNode * root){
printf("%d ",root->value);
}
void preOrder(BTreeNode* root){
if(root != NULL){
visit(root);
}
if(root->lchild != NULL){
preOrder(root->lchild);
}
if(root->rchild !=NULL){
preOrder(root->rchild);
}
}
void inOrder(BTreeNode* root){
if(root->lchild != NULL){
inOrder(root->lchild);
}
if(root != NULL){
visit(root);
}
if(root->rchild !=NULL){
inOrder(root->rchild);
}
}
void postOrder(BTreeNode* root){
if(root->lchild != NULL){
postOrder(root->lchild);
}
if(root->rchild !=NULL){
postOrder(root->rchild);
}
if(root != NULL){
visit(root);
}
}
void BFSVisit(BTreeNode* root){
if(root == NULL){
return ;
}
queue<BTreeNode*> que;
que.push(root);
while(!que.empty()){
BTreeNode *tmp = que.front();
que.pop();
visit(tmp);
if(tmp->lchild != NULL){
que.push(tmp->lchild);
}
if(tmp->rchild != NULL){
que.push(tmp->rchild);
}
}
}
void non_recur_preOrder(BTreeNode * root){
stack<BTreeNode *> s;
BTreeNode * tmp = root;
while(tmp != NULL|| !(s.empty())){
while(tmp != NULL){
visit(tmp);
s.push(tmp);
tmp = tmp->lchild;
}
while(!(s.empty())){
tmp = s.top();
s.pop();
tmp = tmp->rchild;
}
}
}
void non_recur_inOrder(BTreeNode * root){
stack<BTreeNode *> s;
BTreeNode * tmp = root;
while(tmp != NULL|| !(s.empty())){
while(tmp != NULL){
s.push(tmp);
tmp = tmp->lchild;
}
while(!(s.empty())){
tmp = s.top();
visit(tmp);
s.pop();
tmp = tmp->rchild;
}
}
}
void non_recur_postOrder(BTreeNode *root){
stack<int> tag;
stack<BTreeNode *> s;
BTreeNode* tmp = root;
do{
while(tmp != NULL){
s.push(tmp);
tag.push(0);
tmp = tmp->lchild;
}
while(!s.empty() && tag.top()==1){
tmp = s.top();
s.pop();
tag.pop();
visit(tmp);
}
if(!s.empty()){
tag.pop();
tag.push(1);
tmp = (s.top())->rchild;
}
}while(!(s.empty()));
}
main(){
BTreeNode * root;
root = createTree();
printf("preOrder :");
preOrder(root);
printf("\n");
printf("preOrder :");
non_recur_preOrder(root);
printf("\n");
printf("inOrder :");
inOrder(root);
printf("\n");
printf("inOrder :");
non_recur_inOrder(root);
printf("\n");
printf("postOrder :");
postOrder(root);
printf("\n");
printf("postOrder :");
non_recur_postOrder(root);
printf("\n");
system("pause");
return 0;
}
【学习点滴 -数据结构-二叉树】 二叉树的遍历(全)
最新推荐文章于 2024-09-16 18:31:59 发布