我的二叉树的遍历都是用递归实现的。二叉树的创建就不再说了,如果不懂可以看这几篇文章。
http://blog.youkuaiyun.com/liuzuyi200/article/details/24232937
二叉树的几种实现方式(1)数组法
http://blog.youkuaiyun.com/liuzuyi200/article/details/24232453
所谓的遍历是以根节点做标准的,若根节点在左中右三个结点中最先输出,叫前序遍历,
以此类推,,若根节点在左中右三个结点中第二个输出,叫中序遍历,若根节点在左中右三个结点中最后输出,叫后序遍历,
(1)前序遍历的实现过程
void perorder( btree ptr)
{
if( ptr != NULL )
{
printf("[%2d]\n",ptr->data);
perorder( ptr->left );
perorder(ptr->right);
}
}
(2)中序遍历的实现过程
void inorder( btree ptr)
{
if( ptr != NULL )
{
inorder( ptr->left );
printf("[%2d]\n",ptr->data);
inorder(ptr->right);
}
}
(3)后序遍历的实现过程
void postorder( btree ptr)
{
if( ptr != NULL )
{
postorder( ptr->left );
postorder(ptr->right);
printf("[%2d]\n",ptr->data);
}
}
实现的过程
#include<stdio.h>
#include<stdlib.h>
struct tree
{
int data;
struct tree *left;
struct tree *right;
};
typedef struct tree treenode;
typedef treenode *btree;
btree insert_node( btree root ,int value)
{
btree newnode;
btree current;
btree back;
newnode = (btree ) malloc(sizeof(treenode));
newnode->data = value;
newnode->left = NULL;
newnode->left = NULL;
if( root == NULL )
{
return newnode;
}
else
{
current = root;
while(current != NULL )
{
back = current;
if( current->data > value )
current = current->left;
else
current = current->right;
}
if(back->data > value)
back->left =newnode;
else
back->right =newnode;
}
return root;
}
btree creatbtree( int *data,int len )
{
btree root = NULL;
int i;
for( i = 0; i < len ; i++)
{
root = insert_node( root , data[i] );
}
return root;
}
void postorder( btree ptr)
{
if( ptr != NULL )
{
postorder( ptr->left );
postorder(ptr->right);
printf("[%2d]\n",ptr->data);
}
}
void perorder( btree ptr)
{
if( ptr != NULL )
{
printf("[%2d]\n",ptr->data);
perorder( ptr->left );
perorder(ptr->right);
}
}
void inorder( btree ptr)
{
if( ptr != NULL )
{
inorder( ptr->left );
printf("[%2d]\n",ptr->data);
inorder(ptr->right);
}
}
int main()
{
btree root = NULL;
int data[9] ={5,6,4,8,2,3,7,1,9};
root = creatbtree(data,9);
printf("树的结点内容\n");
postorder(root);
inorder(root);
perorder(root);
return 0 ;
}