如何看树

时间:2019-02-01 03:47:36

标签: c data-structures tree

语言是C。我必须阅读l​​eftmostChild-rightSibling表示形式的树。定义是:

#use "Yojson";;
#use "yojson";;
#require "Yojson";;
#require "yojson";;

我需要功能:

typedef struct Node *pNode;
struct Node {
    int data;
    pNode parent, leftmostChild, rightSibling;
}

该函数将在堆中创建树并返回指向它的指针。所有信息都将从控制台中的用户那里获取。例如,将为root读取数据字段。

然后将询问用户根有多少个孩子,并读取每个孩子的子树。

如何编写这样的功能?

1 个答案:

答案 0 :(得分:0)

如果有人对解决方案感兴趣,那就是:

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

typedef struct Node *pNode;
struct Node {
  int data;
  pNode leftmostChild, rightSibling;
};

pNode read_pNode( void )
{
  int n;
  pNode p = malloc(sizeof( struct Node ) );
  printf("Input the node label (int ):");
  scanf("%d", &(p->data) );
  p->leftmostChild = NULL;
  p->rightSibling = NULL;
  printf("Input the number of children fot this node (0 for none): ");
  scanf("%d", &n);
  if( n == 0 ) return p;
  pNode *q = malloc( sizeof( pNode) * n );
  for( int j = 0; j < n ; j++ ) q[j]=read_pNode();
  p->leftmostChild = *q;
  for( int j = 0; j < n-1; j++ )
    q[j]->rightSibling = q[j+1];
  q[n-1]->rightSibling = NULL;
  free(q);
  return p;
}

void preorder_pNode( pNode p)
{
  pNode q;
  printf("%d ", p->data);
  q = p->leftmostChild;
  while( q != NULL ) {
    preorder_pNode( q );
    q = q -> rightSibling;
  }
}

int main(void)
{
  pNode p=read_pNode();
  preorder_pNode(p);
  return 0;
}

这是一个更困难的问题。如何释放read_pNode分配的内存?