首页 > 学院 > 开发设计 > 正文

二叉树:由已知的遍历方式求另外的遍历方式

2019-11-08 01:13:05
字体:
来源:转载
供稿:网友

已知前序和中序,求后序

struct node *creat(char *a, char *b, int n)  {   struct node *ptr;   char *p;   int count = 0;   if (n <= 0)     return NULL;    ptr = (struct node *)malloc(sizeof(struct node));    ptr -> data = *a;    for (p = &b[0]; p <= b + n - 1;p ++)    {     if (*p == *a)       break;    }    count = p - b;    ptr -> l = creat(a + 1, b, count);    ptr -> r = creat(a + 1 + count, p + 1, n - 1 - count);   return ptr;  }
已知中序和后序,求前序
struct node *creat(char *a, char *b, int n)  {   struct node *ptr;   if (n <= 0)     return NULL;    ptr = (struct node *)malloc(sizeof(struct node));    ptr -> data = b[n - 1];   int q = strchr(a, b[n - 1]) - a;   ptr -> l = creat(a, b, q);   ptr -> r = creat(a + q + 1, b + q, n - q - 1);   return ptr;  }
已知前序和中序,求层序
struct node *creat(int n, char *a, char *b){    int i;    struct node *root;    if(n == 0) return NULL;    root = (struct node *) malloc(sizeof(struct node));    root -> data = a[0];    for(i = 0; i < n; i++)    {        if(b[i] == a[0])            break;    }    root -> l = creat(i, a+1, b);    root -> r = creat(n-1-i, a+i+1, b+i+1);    return root;};

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表