简体   繁体   English

从二叉树创建链接列表(预遍历)

[英]Creating a linked list from a binary tree (preorder tranversal)

So I'm trying to create a linked list from a binary tree using preorder tranversal. 所以我试图使用预顺序遍历从二叉树创建一个链表。 I'm having so many problems at doing it, I saw some of the "solutions" but I didn't like it! 我在执行时遇到很多问题,我看到了一些“解决方案”,但我不喜欢它! I am trying something simple. 我正在尝试一些简单的事情。

This is the code that I got until now: 这是我到目前为止获得的代码:

typedef struct nodo {
  int value;
  struct nodo *left, *right;
} *ABin;

typedef struct lligada { 
  int value;
  struct lligada *next;
} *LInt;

void preorder (ABin a, LInt * l) {

  LInt r=*l,tmp;
  tmp=r;

  if (!a) {
    *l=NULL;
}
  else {
    r=malloc(sizeof(struct lligada));
    r->value=a->value;
    r=r->next;
    *l=tmp;
    preorder (a->left,l);
    preorder (a->right,l);
  }
}

I'm getting always an empty list! 我总是空着清单!

if (!a) { *l=NULL; 如果(!a){* l = NULL; } }

This will allways be the last thing done in your function, with the null in *l being passed all the way up. 这将永远是函数中要做的最后一件事,* l中的null会一直传递。

The rest also has problems: 其余的也有问题:

r=r->next; r = r-> next;

But you never set r->next to anything. 但是,您永远不会将r->next设置为任何东西。 You'll have to do that first. 您必须先这样做。

Further, when you first call preorder() what, if anything, is *l pointing to? 此外,当您第一次调用preorder()*l指向什么? You'd probably be better off, instead of passing in a LInt*, having the function return a Lint* (joining the lists after the internal calls to preorder() ) 您可能会更好,而不是传递LInt *,而让函数返回Lint *(在内部调用preorder()之后加入列表)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM