当前位置: 首页 > news >正文

数据结构:完全二叉树(递归实现)

       如果完全二叉树的深度为h,那么除了第h层外,其他层的节点个数都是满的,第h层的节点都靠左排列。

       完全二叉树的编号方法是从上到下,从左到右,根节点为1号节点,设完全二叉树的节点数为sum,某节点编号为i,

       当2*i <= sum时,有左孩子,其编号为2*i,否则没有左孩子,本身为叶节点。

       当2*i+1 <= sum时,有右孩子,其编号为2*i+1,否则没有右孩子。

tree.h

/*===============================================
*   文件名称:tree.h
*   创 建 者:cxy     
*   创建日期:2024年01月23日
*   描    述:
================================================*/
#ifndef _TREE_H
#define _TREE_H#include <stdio.h>
#include <stdlib.h>typedef struct node{int data;struct node *lchild;struct node *rchild;
}Tree,*Ptree;Ptree init(int i,int sum); //i为节点编号,sum为总数
int preorder(Ptree root);  //先序遍历
int inorder(Ptree root);   //中序遍历
int postorder(Ptree root); //后序遍历#endif

tree.c

/*===============================================
*   文件名称:tree.c
*   创 建 者:cxy     
*   创建日期:2024年01月23日
*   描    述:
================================================*/
#include "tree.h"Ptree init(int i,int sum)
{Ptree root = malloc(sizeof(Tree));root->data = i;if(2*i <= sum){root->lchild = init(2*i,sum);}else{root->lchild = NULL;}if(2*i+1 <= sum){root->rchild = init(2*i+1,sum);}else{root->rchild = NULL;}return root;
}int preorder(Ptree root)
{if(NULL == root)return 0;printf("%d ",root->data);preorder(root->lchild);preorder(root->rchild);return 0;
}int inorder(Ptree root)
{if(NULL == root)return 0;inorder(root->lchild);printf("%d ",root->data);inorder(root->rchild);return 0;
}int postorder(Ptree root)
{if(NULL == root)return 0;postorder(root->lchild);postorder(root->rchild);printf("%d ",root->data);return 0;
}

main.c

/*===============================================
*   文件名称:main.c
*   创 建 者:cxy     
*   创建日期:2024年01月23日
*   描    述:
================================================*/
#include "tree.h"int main(int argc, char *argv[])
{ Ptree root;root = init(1,9);printf("-----先序遍历-----\n");preorder(root);puts("");printf("-----中序遍历-----\n");inorder(root);puts("");printf("-----后序遍历-----\n");postorder(root);puts("");return 0;
} 

结果

http://www.lryc.cn/news/286210.html

相关文章:

  • RK3568 移植Ubuntu
  • C++大学教程(第九版)6.34猜数字游戏 6.35 修改的猜数字游戏
  • 【立创EDA-PCB设计基础】5.布线设计规则设置
  • ElementUI简介以及相关操作
  • 内存耗尽排查思路
  • OpenCV书签 #差值哈希算法的原理与相似图片搜索实验
  • Unity中URP下获取主灯信息
  • 尝试着在Stable Diffusion里边使用SadTalker进行数字人制作
  • 链路聚合原理与配置
  • 第8章 通信网络安全
  • L1-092 进化论(Java)
  • SpringBoot 源码解析5:ConfigurationClassPostProcessor整体流程和@ComponentScan源码分析
  • 一.初识Linux 1-3操作系统概述Linux初识虚拟机介绍
  • Eureka整合seata分布式事务
  • 华为云磁盘性能指标(参考)
  • 利用OpenGL图形库实现人物动画移动效果
  • History命令解释,及一个相关的bash脚本(如何编写脚本程序从记录文件中提取history命令)
  • apisix 单机部署 linux
  • Redis 面试题 | 06.精选Redis高频面试题
  • 2008年苏州大学837复试机试C/C++
  • MySQL笔记-information_schema库中COLUMNS表的一些笔记
  • 归并排序模板
  • 【NVIDIA】Jetson Orin Nano系列:安装 Qt6、firefox、jtop、flameshot
  • Fastapi+Jsonp实现前后端跨域请求
  • MacOS受欢迎的数据库开发工具 Navicat Premium 15 中文版
  • helm---自动化一键部署
  • 求助帖(setiosflags)的左右对齐问题:
  • 升级8.0:民生手机银行的“内容解法”
  • Kubernetes多租户实践
  • 【GEE】GEE反演地表温度相关问题说明(空洞、Landsat9数据集等)