二叉树的遍历

二叉树的遍历
#include"iostream"
#include
"stdlib.h"
using namespace std;

struct tree
{
int data;
struct tree *left;
struct tree *right;
};

typedef
struct tree treenode;
typedef treenode
*btree;


/*------插入二叉树的结点-------*/
btree insertnode(btree root,
int value)
{
btree newnode;
btree current;
btree back;


/*---创建新结点内存---*/

newnode
=(btree)malloc(sizeof(treenode));
newnode
->data=value;
newnode
->right=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 createbtree(
int *data, int len)
{
btree root
=NULL;
int i;
for(i=0;i<len;i++)
root
=insertnode(root,data[i]);
return root;
}
/*-----中序遍历------*/
void inorder( btree ptr)
{
if(ptr!=NULL)
{
inorder(ptr
->left);
printf(
"[%2d]\n",ptr->data);
inorder(ptr
->right);
}
}
/*-----------------------*/

/*--------前序遍历-------*/

void preorder(btree ptr)
{
if(ptr!=NULL)
{

printf(
"[%2d]\n",ptr->data);
inorder(ptr
->left);
inorder(ptr
->right);
}
}
/*-----------------------------*/

/*------后序遍历--------*/

void postorder(btree ptr)
{
if(ptr!=NULL)
{

inorder(ptr
->left);
inorder(ptr
->right);
printf(
"[%2d]\n",ptr->data);

}
}
/*---------------------------*/

/*---------主程序-----*/

int main()
{
btree root
=NULL;

int data[9]={5,6,4,8,2,3,7,1,9};
root
=createbtree(data,9);
printf(
"树的结点内容:\n");
inorder(root);
cout
<<endl;
preorder(root);
cout
<<endl;
postorder(root);
cout
<<endl;

}

 

posted @ 2010-11-22 20:49  聊聊IT那些事  阅读(296)  评论(0编辑  收藏  举报