首页 > 解决方案 > 在二叉树 adt 上传递的错误值导致错误的输出

问题描述

所以我尝试使用数组实现来制作二叉树。我刚开始,但我遇到了问题。首先,这是我用来为树构建节点的结构

typedef char infotype;
typedef int letak; //it's the variable to tell the array position number
typedef struct simpul
{
  infotype info;
  letak parent;
  letak rightSon, leftSon;
}elemenSimpul;

typedef struct 
{
  elemenSimpul treeMember[30]; //my tree have very maximum 30 nodes in it.
  int maksimum; //it's the variable to put how many node the user wants and should be under 30
}tree;

这是我的 btreestatic.h

#ifndef btreestatic_H
#define btreestatic_H
void createTree(tree T);
void createNode(tree T, int i, char value);
void initNode(tree T, int i);
#endif

为了构建树,我在我的 btreestatic.c 中使用了这些

#ifndef btreestatic_C
#define btreestatic_C

#include <stdio.h>
#include <math.h>
#include "btreestatic.h"

void createTree(tree T)
{
   T.treeMember[0].parent = -1;
}

void createNode(tree T,int i, char value)
{
  int leftchild;
  int rightchild;

  T.treeMember[i].info = value;

  leftchild = 2 * i + 1;
  rightchild = 2 * i + 2;

  if(leftchild < T.maksimum)
  {
     T.treeMember[i].leftSon = leftchild;
  }
  else
  {
    T.treeMember[i].leftSon = -1;
  }

  if (rightchild < T.maksimum)
  {
    T.treeMember[i].rightSon = rightchild;
  }
  else
  {
    T.treeMember[i].rightSon = -1;
  }

  if(i == 0)
  {
     T.treeMember[i].parent = -1;
  }
  else
  {
     T.treeMember[i].parent = (i - 1) / 2;
  }
}

void initNode(tree T, int i)
{
  char info;

  printf("Input node info : ");
  scanf(" %c", &info);

  createNode(T, i, info);
}
#endif

我的司机是

#include <stdio.h>
#include <stdlib.h>
#include "btreestatic.h"


int main() 
{
  tree A;
  int maksimum;
  int j;

  createTree(A);
  scanf("%d", &maksimum);
  A.maksimum = maksimum;


  for(j = 0; j < A.maksimum; j ++)
  {
     initNode(A, j);
  }

  printf("%c", A.treeMember[0].info);


  return 0;
 }

然后我尝试输入为 3(树节点的最大值为 3)。第一个节点(根)是'a',第二个节点是'b',第三个节点是'c'。但是我在屏幕上看到的是'd'而不是'a'。谁能告诉我我哪里出错了?谢谢你。

标签: cfunctionbinary-treeadt

解决方案


推荐阅读