1.思路
先序遍历:遍历顺序 root、leftchild、rightchild
中序遍历:遍历顺序leftchild、root、rightchild
后序遍历:遍历顺序leftchild、rightchild、root
“先中后”指的是根结点root在遍历顺序中的相对位置。程序中分别用递归与非递归方法实现,递归方法较为简单,非递归方法采用堆栈stack进行辅助操作。
2.代码
#include<iostream>
using namespace std;
struct node {
int value;
node* lchild;
node* rchild;
};
//0表示空结点
node* create() {
int value;
node* root;
cin >> value;
if(value == 0) {
root = NULL;
} else {
root = (node*)malloc(sizeof(node));
root->value = value;
cout << "please input (" << value << ") its leftchild node" << endl;
root->lchild = create();
cout << "please input (" << value << ") its rightchild node" << endl;
root->rchild = create();
}
return root;
}
//0表示空结点,init()不对树的结点赋值
node* init() {
int value;
node* root;
cin >> value;
if(value == 0) {
root = NULL;
return root;
} else {
root = (node*)malloc(sizeof(node));
cout << "please input (" << value << ") its leftchild node" << endl;
root->lchild = init();
cout << "please input (" << value << ") its rightchild node" << endl;
root->rchild = init();
return root;
}
}
void visit(node* p) {
cout << p->value << " ";
}
//递归版先序遍历
void preorder(node* p) {
if(p == NULL) {
return;
}
visit(p);
preorder(p->lchild);
preorder(p->rchild);
}
//非递归版先序遍历
void preorder1(node* p) {
node* stack[100];
int ntop = 0;
node* cur = p;
while(cur != NULL || ntop > 0) {
while(cur != NULL) { //访问所以左孩子节点,并依次入栈
visit(cur);
stack[ntop++] = cur;
cur = cur->lchild;
}
if(ntop > 0) {
cur = stack[--ntop]->rchild;
}
}
}
void inorder(node* p) {
if(p == NULL) {
return;
}
inorder(p->lchild);
visit(p);
inorder(p->rchild);
}
void inorder1(node* p) {
node* stack[100];
int ntop = 0;
node* cur = p;
while(cur != NULL || ntop > 0) {
while(cur != NULL) {
stack[ntop++] = cur;
cur = cur->lchild;
}
if(ntop > 0) {
cur = stack[--ntop];
visit(cur);
cur = cur->rchild;
}
}
}
void posorder(node* p) {
if(p == NULL) {
return;
}
posorder(p->lchild);
posorder(p->rchild);
visit(p);
}
void posorder1(node* p) {
node* stack[100];
int ntop = 0;
node* cur = p;
node* lastvisit = NULL;
while(cur != NULL || ntop > 0) {
while(cur != NULL) {
stack[ntop++] = cur;
cur = cur->lchild;
}
cur = stack[ntop - 1];
if(cur->rchild == NULL || cur->rchild == lastvisit) {
visit(cur);
ntop--;
lastvisit = cur;
cur = NULL; //cur = NULL 只是把cur清除,原二叉树的结点并没有变化!
} else {
cur = cur->rchild;
}
}
}
int main() {
cout << "please input the tree" << endl;
node* p = create();
cout << "preorder: ";
preorder1(p);
cout << endl;
cout << "inorder: ";
inorder1(p);
cout << endl;
cout << "posorder: ";
posorder1(p);
cout << endl;
return 0;
}
3.运行结果