设为首页 - 加入收藏 ASP站长网(Aspzz.Cn)- 科技、建站、经验、云计算、5G、大数据,站长网!
热搜: 创业者 手机 数据
当前位置: 首页 > 综合聚焦 > 编程要点 > 语言 > 正文

树的双亲表示法 包含C语言达成代码

发布时间:2022-07-07 10:09 所属栏目:51 来源:互联网
导读:前面讲了二叉树的顺序存储和链式存储,本节来学习如何存储具有普通树结构的数据。 普通树的过程转化为 C 语言代码为: #define MAX_SIZE 100//宏定义树中结点的最大数量 typedef char ElemType;//宏定义树结构中数据类型 typedef struct Snode{ TElemType da
  前面讲了二叉树的顺序存储和链式存储,本节来学习如何存储具有普通树结构的数据。
 
   普通树的过程转化为 C 语言代码为:
  #define MAX_SIZE 100//宏定义树中结点的最大数量
  typedef char ElemType;//宏定义树结构中数据类型
  typedef struct Snode{
      TElemType data;//树中结点的数据类型
      int parent;//结点的父结点在数组中的位置下标
  }PTNode;
  typedef struct {
      PTNode tnode[MAX_SIZE];//存放树中所有结点
      int n;//根的位置下标和结点数
  }PTree;
 
  因此,存储图 1 中普通树的 C 语言实现代码为:
  #include<stdio.h>
  #include<stdlib.h>
  #define MAX_SIZE 20
  typedef char ElemType;//宏定义树结构中数据类型
  typedef struct Snode  //结点结构
  {
      ElemType data;
      int parent;
  }PNode;
  typedef struct  //树结构
  {
      PNode tnode[MAX_SIZE];
      int n;                 //结点个数
  }PTree;
  PTree InitPNode(PTree tree)
  {
      int i, j;
      char ch;
      printf("请输出节点个数:\n");
      scanf("%d", &(tree.n));
      printf("请输入结点的值其双亲位于数组中的位置下标:\n");
      for (i = 0; i < tree.n; i++)
      {
          getchar();
          scanf("%c %d", &ch, &j);
          tree.tnode[i].data = ch;
          tree.tnode[i].parent = j;
      }
      return tree;
  }
  void FindParent(PTree tree)
  {
      char a;
      int isfind = 0;
      printf("请输入要查询的结点值:\n");
      getchar();
      scanf("%c", &a);
      for (int i = 0; i < tree.n; i++) {
          if (tree.tnode[i].data == a) {
              isfind = 1;
              int ad = tree.tnode[i].parent;
              printf("%c的父节点为 %c,存储位置下标为 %d", a, tree.tnode[ad].data, ad);
              break;
          }
      }
      if (isfind == 0) {
          printf("树中无此节点");
      }
  }
  int main()
  {
      PTree tree;
      for (int i = 0; i < MAX_SIZE; i++) {
          tree.tnode[i].data = " ";
          tree.tnode[i].parent = 0;
      }
     
      tree = InitPNode(tree);
      FindParent(tree);
      return 0;
  }
  程序运行示例:
  请输出节点个数:
  10
  请输入结点的值其双亲位于数组中的位置下标:
  R -1
  A 0
  B 0
  C 0
  D 1
  E 1
  F 3
  G 6
  H 6
  K 6
  请输入要查询的结点值:
  C
  C的父节点为 R,存储位置下标为 0

(编辑:ASP站长网)

    网友评论
    推荐文章
      热点阅读