二叉树创建、遍历、插入

#include<bits/stdc++.h>
using namespace std;
typedef struct node;
typedef node *tree;
struct node
{
	int data;
	tree lchild, rchild; 
};
tree bt;
void pre_crt(tree &bt) //按先序次序输入二叉树中结点的值,生成
	{
		int ch;
		cin>>ch;  //二叉树的单链表存储结构,bt为指向根结点的指针,'$'表示空树 
		if(ch!=0)
		{
			bt = new node;      //建根结点
			bt->data = ch;
			pre_crt(bt->lchild);  //建左子树
			pre_crt(bt->rchild);  //建右子树
		}
		else bt = NULL;
		return;
	}
void preorder(tree bt)  //先序遍历根结点为bt的二叉树的递归算法
	{
	    if(bt)
	   {
	      cout << bt->data;
	      preorder(bt->lchild);
	      preorder(bt->rchild);
	   }
	}
void inorder(tree bt)  //中序遍历根结点为bt的二叉树的递归算法
{
    if(bt)
    {
	inorder(bt->lchild);
	cout << bt->data<<" ";
	inorder(bt->rchild);
    }
}
void postorder(tree bt)  //后序遍历根结点为bt的二叉树的递归算法
	{
  	  if(bt)
	    {
 	       postorder(bt->lchild);
  	      postorder(bt->rchild);
 	       cout << bt->data;
 	   }
	}
void insert(tree &bt, int n)    //插入一个结点到排序二叉树中
	{
		if(bt)
		{
			if(n < bt->data) insert(bt->lchild, n);
			else if(n > bt->data) insert(bt->rchild, n);
		}
		else
		{
			bt = new node;      //新开一个空间
			bt->data = n;
			bt->lchild = bt->rchild = NULL;
		}
	}	


int main()
{
 pre_crt(bt);
 //preorder(bt);cout<<endl;
 inorder(bt);cout<<endl;
//postorder(bt);cout<<endl;
insert(bt,5);insert(bt,40);
 inorder(bt);cout<<endl;	
}//AB##c##
//ABD##C##E##
//20 10 0 0 30 0 0

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值