标签:
#include<stdio.h>
#include<stdlib.h>
#include<queue>
#include<stack>
#include<iostream>
using namespace std;
struct node{
int key;
node *left, *right;
};
void insertTree(node* &root,int val)
{
node* tmp = (node*)malloc(sizeof(node));
tmp->key = val;
tmp->left = tmp->right = NULL;
node *q = NULL, *p = root;
while (p){
q = p;
if (p->key > val) p = p->left;
else if (p->key < val) p = p->right;
else return;
}
if (q == NULL) root = tmp;
else if (q->key > val) q->left = tmp;
else q->right = tmp;
}
//非递归遍历
//层序遍历
void printByLevel(node *root)
{
node *p;
queue<node*> q;
q.push(root);
while (!q.empty()){
p = q.front(); q.pop();
if (p){
printf("%d ", p->key);
q.push(p->left);
q.push(p->right);
}
}
printf("\n");
}
//中序遍历
void printByInorder(node* root)
{
stack<node*> s;
node *p = root;
while (p || !s.empty()){
while (p){
s.push(p);
p = p->left;
}
if (!s.empty()){
p = s.top(); s.pop();
printf("%d ", p->key);
p = p->right;
}
}
printf("\n");
}
//前序遍历
void printByPreorder(node* root)
{
stack<node*> s;
node* p = root;
while (p||!s.empty()){
while (p){
printf("%d ", p->key);
s.push(p);
p = p->left;
}
if (!s.empty()){
p = s.top(); s.pop();
p = p->right;
}
}
printf("\n");
}
//后序遍历
void printByPostorder(node *root)
{
stack<node*> s;
node* p = root;
while (p || !s.empty()){
while (p){
printf("%d ", p->key);
s.push(p);
p = p->right;
}
if (!s.empty()){
p = s.top(); s.pop();
p = p->left;
}
}
printf("\n");
}
//递归遍历
void inorder(node* root)
{
if (root){
inorder(root->left);
printf("%d ", root->key);
inorder(root->right);
}
}
void preorder(node* root){
if (root){
printf("%d ", root->key);
preorder(root->left);
preorder(root->right);
}
}
void postorder(node* root)
{
if (root){
postorder(root->left);
postorder(root->right);
printf("%d ", root->key);
}
}
int main()
{
node *root = NULL;
int a[] = { 8, 4, 12, 2, 6, 10, 14, 3, 5, 7, 13 };
for (int i = 0; i < 11; ++i)
insertTree(root, a[i]);
printf("Recursive Traversal : inorder preorder postorder\n");
inorder(root);
printf("\n");
preorder(root);
printf("\n");
postorder(root);
printf("\n");
printf("Iteration Traversal : level inorder preorder postorder\n");
printByLevel(root);
printByInorder(root);
printByPreorder(root);
printf("Postorder Traversal print in reverse: ");
printByPostorder(root);
}
对于后序遍历的非递归实现,该程序中是以相反的方向输出的,可以使用vector,实现正确方向。
标签:
原文地址:http://www.cnblogs.com/jokoz/p/4733679.html