二叉树

简单的二叉树的创建和前中后遍历

#include <stdio.h>
#include <iostream>
char Nil='#';//空结点的标志
using namespace std;
//结点定义
struct node
{
    char data;//数据
    node *leftchild;//左指针
    node *rightchild;//右指针
};
void CreateBiTree(node* &T)
{
    //用前序遍历的方式建立二叉树
    //变量Nil表示空(子)树
    char ch;
    cin>>ch;
    if(ch==Nil)
    {
        T=NULL;
    }
    else
    {
        T=new node;
        T->data=ch;
        CreateBiTree(T->leftchild);
        CreateBiTree(T->rightchild);
    }
}
//================================================中序遍历二叉树
void Inorder(node* T){//中序递归遍历二叉树
 if(T){//bt=null退层
  Inorder(T->leftchild);//中序遍历左子树
  cout<<T->data;//访问参数
  Inorder(T->rightchild);//中序遍历右子树
 }
 else cout<<"";
 }
 //===============================================先序递归遍历二叉树
void PreOrderTraverse(node* &T){
 //先序递归遍历二叉树
 if(T){//当结点不为空的时候执行
  cout<<T->data;
  PreOrderTraverse(T->leftchild);//
  PreOrderTraverse(T->rightchild);
 }
 else cout<<"";
}
//=================================================后序递归遍历二叉树
void Posorder(node* &T){
 if(T){
  Posorder(T->leftchild);//后序递归遍历左子树
  Posorder(T->rightchild);//后序递归遍历右子树
  cout<<T->data;//访问根结点
 }
 else cout<<"";
}

int main()
{
    freopen("in.txt","r",stdin);
    node *T;//二叉树根节点
    CreateBiTree(T);
    cout<<"前序遍历的结果"<<endl;
    PreOrderTraverse(T);cout<<endl;
    cout<<"中序遍历的结果"<<endl;
    Inorder(T);cout<<endl;
    cout<<"后序遍历的结果"<<endl;
    Posorder(T);cout<<endl;
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值