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

王道数据结构课后代码题p175 06.已知一棵树的层次序列及每个结点的度,编写算法构造此树的孩子-兄弟链表。(c语言代码实现)

 /* 此树为

              A

        B         C        D

E        F     G

孩子-兄弟链表为

                        A

                B        

        E           C

           F     G        D

*/

本题代码如下

void createtree(tree* t, char a[], int degree[], int n)
{// 为B数组分配内存tree* B = (tree*)malloc(sizeof(tree) * n);int i = 0;int j = 0;int k = 0;int d = 0;for (i = 0; i < n; i++) {B[i] = (tree)malloc(sizeof(treenode)); // 为每个节点分配内存B[i]->data = a[i];B[i]->lchild = B[i]->rborther = NULL;}for (i = 0; i < n; i++) {d = degree[i];if (d) {k++;B[i]->lchild = B[k];for (j = 2; j <= d; j++) {k++;B[k - 1]->rborther = B[k];}}}*t = B[0]; // 返回根节点
}

完整测试代码为

#include<stdio.h>
#include<stdlib.h>
typedef struct treenode
{char data;struct treenode* lchild, * rborther;
} treenode, * tree;
void createtree(tree* t, char a[], int degree[], int n)
{// 为B数组分配内存tree* B = (tree*)malloc(sizeof(tree) * n);int i = 0;int j = 0;int k = 0;int d = 0;for (i = 0; i < n; i++) {B[i] = (tree)malloc(sizeof(treenode)); // 为每个节点分配内存B[i]->data = a[i];B[i]->lchild = B[i]->rborther = NULL;}for (i = 0; i < n; i++) {d = degree[i];if (d) {k++;B[i]->lchild = B[k];for (j = 2; j <= d; j++) {k++;B[k - 1]->rborther = B[k];}}}*t = B[0]; // 返回根节点
}
void print(tree* t)//先序输出树结点
{if (*t) {printf("%c ", (*t)->data); print(&(*t)->lchild);print(&(*t)->rborther);}
}
int main()
{tree t;char a[7] = "ABCDEFG";int degree[7] = { 3,2,1,0,0,0,0 };createtree(&t, a, degree, 7);print(&t);return 0;
}

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

相关文章:

  • filter过滤器
  • MES物料的动态批次管理漫谈
  • 【爬虫逆向分析实战】某笔登录算法分析——本地替换分析法
  • vue3使用动态component
  • 单机游戏推荐:巨击大乱斗 GIGABASH 中文安装版
  • 计算机系统启动过程
  • DedeCms后台文章列表文档id吗?或者快速定位id编辑文章
  • 【开发问题解决方法记录】03.dian
  • QT之QString
  • 常见的几种计算机编码格式
  • 3D旋转tab图
  • openGL 三:矩阵和向量
  • Socket和Http的通讯原理,遇到攻击会受到哪些影响以及如何解决攻击问题。
  • 【springboot】整合redis
  • 回溯和分支算法
  • 深入理解:指针变量的解引用 与 加法运算
  • Docker 镜像构建的最佳做法
  • 工作上Redis安装及配置
  • 电商项目之Web实时消息推送(附源码)
  • 上机实验四 哈希表设计 西安石油大学数据结构
  • Ubuntu22.04 交叉编译mp4V2 for Rv1106
  • 缓存穿透、击穿、雪崩
  • (1w字一篇理解透Unsafe类)Java魔法类:Unsafe详解
  • Python的正则表达式使用
  • Elasticsearch:评估 RAG - 指标之旅
  • 【2023.12.4练习】数据库知识点复习测试
  • 【wvp】测试记录
  • 【若依框架实现上传文件组件】
  • 玩转大数据5:构建可扩展的大数据架构
  • 【华为数据之道学习笔记】非数字原生企业的特点