树中的指针重建功能

时间:2014-05-08 20:44:58

标签: c pointers binary-tree

任何人都可以帮我理解我的代码中的这些注释和警告吗?特别是它所说的expected 'struct node**' but argument is of type 'struct node *' "部分。 此外,在递归调用:

tree_rebuild((*sroot)->esq, pOrd, emOrd, start, emOrd_index - 1);

使用(*sroot)->esq是否正确?

submission.c: In function ‘tree_rebuild’:
submission.c:42:3: warning: passing argument 1 of ‘tree_rebuild’ from incompatible pointer type [enabled by default]
  tree_rebuild((*sroot)->esq, pOrd, emOrd, start, emOrd_index - 1);
  ^
submission.c:11:5: note: expected ‘struct node **’ but argument is of type ‘struct node *’
int tree_rebuild(arv *sroot, char *pOrd, char *emOrd, int start, int end){
    ^
submission.c:43:3: warning: passing argument 1 of ‘tree_rebuild’ from incompatible pointer type [enabled by default]
  tree_rebuild((*sroot)->dir, pOrd, emOrd, emOrd_index +1, end);
  ^
submission.c:11:5: note: expected ‘struct node **’ but argument is of type ‘struct node *’
int tree_rebuild(arv *sroot, char *pOrd, char *emOrd, int start, int end){
    ^

submission.c:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct node{
  char info;
  struct node *dir;
  struct node *esq;
}Tree, *arv;

int tree_rebuild(arv *sroot, char *pOrd, char *emOrd, int start, int end){//l11

  static int preOrd_index = 0;

  *sroot = (Tree*)malloc(sizeof(Tree));

  (*sroot)->esq = NULL;
  (*sroot)->dir = NULL;
  printf("ok\n");

  if(start > end){
    return 0;
  }

  if(start == end){
    (*sroot)->info = emOrd[start];
    return 1;
  }

  int j = start;
  int emOrd_index;

  while(j < end){
    j++;
    if(pOrd[preOrd_index] == emOrd[j]){
      emOrd_index = j;
      break;
    }
  }

  preOrd_index++;
  tree_rebuild((*sroot)->esq, pOrd, emOrd, start, emOrd_index - 1); //l42
  tree_rebuild((*sroot)->dir, pOrd, emOrd, emOrd_index +1, end);    //l43

  return 0;
}

int main(){
  char sPre[100];
  char sEm[100];
  arv root;
  int n, tam;

  scanf("%d", &n);

  while(n){
    scanf("%d", &tam);
    scanf("%s", sPre);
    scanf("%s", sEm);
    tree_rebuild(&root, sPre, sEm, 0, tam-1);

    n--;
  }

  return 0;
}

1 个答案:

答案 0 :(得分:0)

您的递归电话

tree_rebuild((*sroot)->esq, pOrd, emOrd, start, emOrd_index - 1); //l42
tree_rebuild((*sroot)->dir, pOrd, emOrd, emOrd_index +1, end);    //l43

从类型定义中传递struct node *类型的值

typedef struct node{
  char info;
  struct node *dir;
  struct node *esq;
}Tree, *arv;

tree_rebuild期待arv *类型的参数,其中arv *解析为struct node **。以下将修复编译错误。看起来您的代码设置为正确处理双指针。您只是没有传递struct成员的地址,而是传递struct成员的值。

tree_rebuild(&((*sroot)->esq), pOrd, emOrd, start, emOrd_index - 1); //l42
tree_rebuild(&((*sroot)->dir), pOrd, emOrd, emOrd_index +1, end);    //l43