樹的幾種遍歷方式(遞迴/非遞迴)
阿新 • • 發佈:2019-02-02
樹的幾種遍歷方式,前序遍歷,中序遍歷,後序遍歷,包括它的遞迴實現以及非遞迴實現
#include<stdio.h>
#include<stdlib.h>
typedef struct tree
{
int data;
struct tree *left;
struct tree *right;
int flag ;
}*pnode,node;
pnode createbinary(int a[],int n,pnode p);
pnode insertNode(int data,pnode root);
void print(pnode root);
void print1(pnode root);
void print2(pnode root);
void print3(pnode root);
void print4(pnode root);
void print5(pnode root);
void print6(pnode root);
void main()
{
int a[9] = {6,3,8,5,2,9,4,7,11};
pnode root = NULL;
root = createbinary(a,9,root);
print6(root);
free(root);
}
pnode createbinary(int a[],int n,pnode root)
{
for(int i=0; i<n; i++)
{
root = insertNode(a[i],root);
}
return root;
}
pnode insertNode(int value,pnode root)
{
pnode currentnode;
pnode parentnode;
pnode newnode = (pnode)malloc(sizeof(node));
newnode->data = value;
newnode->left = NULL ;
newnode->right = NULL;
if(root == NULL)
{
root = newnode;
}
else
{
currentnode = root;
while(currentnode != NULL)
{
parentnode = currentnode;
if(currentnode->data > value)
currentnode = currentnode->left;
else
currentnode = currentnode->right;
}
if(parentnode->data > value)
{
parentnode->left = newnode;
}
else
{
parentnode->right = newnode;
}
}
return root;
}
void print(pnode root)//後序遍歷
{
if(root != NULL)
{
print(root->left);
print(root->right);
printf("%d\t",root->data);
}
}
void print1(pnode root)//前序遍歷
{
if(root != NULL)
{
printf("%d\t",root->data);
print(root->left);
print(root->right);
}
}
void print2(pnode root)//中序遍歷
{
if(root != NULL)
{
print(root->left);
printf("%d\t",root->data);
print(root->right);
}
}
void print3(pnode root) //層序遍歷,佇列存取
{
pnode q = NULL;
pnode Q[50]= {NULL};
int front = -1,rear = -1;
if(root == NULL)
{
return ;
}
Q[++rear] = root;
while(front != rear)
{
q = Q[++front];
printf("%d\t",q->data);
if(q->left != NULL)
Q[++rear] = q->left;
if(q->right != NULL)
Q[++rear] = q->right;
}
}
void print4(pnode root) //前序遍歷非遞迴
{
int top = -1;
pnode stack[50] = {NULL};
while(top != -1||root != NULL)
{
while(root != NULL)
{
printf("%d\t",root->data);
stack[++top] = root;
root = root->left;
}
if(top != -1)
{
root = stack[top--];
root = root->right;
}
}
}
void print5(pnode root) //中序遍歷非遞迴實現
{
int top = -1;
pnode stack[50] = {NULL};
while(top != -1||root != NULL)
{
while(root != NULL)
{
stack[++top] = root;
root = root->left;
}
if(top != -1)
{
root = stack[top--];
printf("%d\t",root->data);
root = root->right;
}
}
}
void print6(pnode root) //後序遍歷非遞迴演算法
{
int top = -1;
pnode stack[50] = {NULL};
pnode prenode = NULL;
while(top != -1||root !=NULL)
{
while(root !=NULL)//一直找到最左節點
{
stack[++top] = root;
root = root->left;
}
root = stack[top];
if(root->right == NULL || root->right == prenode)//如果右節點被訪問,或者右節點不存在
{
printf("%d\t",root->data);
prenode = root;
top--;
root = NULL;
}
else
{
root = root ->right;
}
}
}