二叉树的遍历

二叉树的遍历
 
   
#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;

}

 

转载于:https://www.cnblogs.com/FCWORLD/archive/2010/11/22/1884749.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值