博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
二叉树的操作(二叉树的创建、先序遍历--->先根、中序遍历---->先左、后续遍历--->后根)
阅读量:4286 次
发布时间:2019-05-27

本文共 1708 字,大约阅读时间需要 5 分钟。

#include "stdlib.h"	#include "stdio.h"	#include "Windows.h"#include 
using namespace std; /*引入头文件*/struct tnode /*定义二叉树存储结构*/{ char data; struct tnode*lchild; struct tnode*rchild;};struct tnode tree; /*定义二叉树指针*/void createtree(struct tnode*t) /*创建函数*/{ struct tnode*p=t; /*把二叉树指针给p*/ char check; if(p->lchild==NULL||p->rchild==NULL) /*判断左右子树是否为空*/ { printf("please enter the data:"); /*输入根结点数据*/ scanf("%c",&(p->data)); getchar(); } if(p->lchild==NULL) { printf("%c leftchild is null.Add? y/n\n",p->data); /*左子树空,询问是否创建*/ scanf("%c",&check); getchar(); if(check=='y') { struct tnode*q=(struct tnode*)malloc(sizeof(struct tnode)); /*开辟空间*/ q->lchild=NULL; q->rchild=NULL; p->lchild=q; createtree(q); } } if(p->rchild==NULL) { printf("%c rightchild is NULL.Add? y/n\n",p->data); /*右子树空,询问是否创建*/ scanf("%c",&check); getchar(); if(check=='y') { struct tnode*q=(struct tnode*)malloc(sizeof(struct tnode)); /*开辟空间*/ q->lchild=NULL; q->rchild=NULL; p->rchild=q; /*连到二叉树上*/ createtree(q); } }}void preorder(struct tnode*t) /*先序遍历函数*/{ if(t) { printf("%c ",t->data); /*输出根结点数据*/ preorder(t->lchild); preorder(t->rchild); }}void inorder(struct tnode*t) /*中序遍历函数*/{ if(t) { inorder(t->lchild); printf("%c ",t->data); inorder(t->rchild); }}void postorder(struct tnode*t) /*后序遍历函数*/{ if(t) { postorder(t->lchild); postorder(t->rchild); printf("%c ",t->data); }}void main(){ //clrscr(); /*清屏函数*/ tree.lchild=NULL; /*左子树*/ tree.rchild=NULL; /*右子树*/ createtree(&tree); /*创建二叉树*/ preorder(&tree); /*先序遍历*/ printf("\n"); inorder(&tree); /*中序遍历*/ printf("\n"); postorder(&tree); /*后序遍历*/}

转载地址:http://wbsgi.baihongyu.com/

你可能感兴趣的文章
C# Windows-API-Code-Pack for .Net
查看>>
C# Windows-API-Code-Pack文件选择对话框实例
查看>>
Vlc.DotNet C#音视频播放器使用说明及简单实例
查看>>
百度音乐Api简单简单实用实例及封装
查看>>
LitJSON .Net开源JSON库、轻量级
查看>>
validateform.js表单验证工具
查看>>
SWFUpload插件-flash上传工具
查看>>
VS2015设置网站/WebSite的启动端口
查看>>
Tesseract.js相关整理
查看>>
echarts(国产)基于html5-canvas的开源图表绘制组件
查看>>
Chart.Js轻量级HTML5图表插件
查看>>
基于Bootstrap的jQuery slider插件的使用bootstrap-slider.js
查看>>
Vue.js数据驱动的组件,为现代化的 Web 界面而生
查看>>
Bootstrap中文网开源项目免费 CDN 服务、cdn.bootcss.com
查看>>
C#发送Get请求(带参数)
查看>>
爬取Ip地址对应的物理位置等信息-百度服务器
查看>>
C# 获取IP地址
查看>>
C#使用ping命令
查看>>
C#域名操作,正则匹配域名
查看>>
VS调试版本和发布版本
查看>>