#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct Node
{
int data;
struct Node* lchild, * rchild;
}Node;
Node* init(int data)
{
Node* node = (Node*)malloc(sizeof(Node));
node->data = data;
node->lchild = NULL;
node->rchild = NULL;
return node;
}
void preorder(Node* node)
{
printf("%c ", node->data);
if (node->lchild != NULL)
{
preorder(node->lchild);
}
if (node->rchild != NULL)
{
preorder(node->rchild);
}
}
void inorder(Node* node)
{
if (node->lchild != NULL)
{
inorder(node->lchild);
}
printf("%c ", node->data);
if (node->rchild != NULL)
{
inorder(node->rchild);
}
}
void pastorder(Node* node)
{
if (node->lchild != NULL)
{
pastorder(node->lchild);
}
if (node->rchild != NULL)
{
pastorder(node->rchild);
}
printf("%c", node->data);
}
void mirrororder(Node* node)
{
if (node->rchild != NULL)
{
mirrororder(node->rchild);
}
if (node->lchild != NULL)
{
mirrororder(node->lchild);
}
printf("%c", node->data);
}
Node* build(char* pre_str, char* in_str, int len)
{
Node* p = init(pre_str[0]);
int pos = strchr(in_str, pre_str[0]) - in_str;
//由于strchr函数返回的是地址,所以需要在函数后面减去首地址in_str,这样才能得到pos
if (pos > 0)//左子树不为空
{
p->lchild = build(pre_str + 1, in_str, pos);
/*先序遍历中pre_str是第0位根节点,第一位开始是左子树的结点,用pre_str+1表从
pre_str第一位以后的字符串,左子树的中序遍历是in_str里第0位开始的字符串
pos中序遍历的长度,根结点前面字符总数,有pos个*/
}
if (len - pos - 1 > 0)
{
p->rchild = build(pre_str + pos + 1, in_str + pos + 1, len - pos - 1);
/*先序遍历pre_str从pos+1开始到末位都是右子树结点,可以用ptr_str+pos+1来表示
表示取pre_str第pos+1位到末位的字符串,中序遍历根节点后的结点都是右子树的结点,用
pre_str+pos+1表示取in_str第pos+1位到末位的字符串,右子树中遍历长度为len-pos-1
*/
}
return p;
}
void clear(Node* node)
{
if (node->lchild != NULL)
{
clear(node->lchild);
}
if (node->rchild != NULL)
{
clear(node->rchild);
}
free(node);
}
int main()
{
char pre_str[51];
scanf("%s", pre_str);
char in_str[51];
scanf("%s", in_str);
Node* root = build(pre_str, in_str, strlen(pre_str));
pastorder(root);
printf("\n");
mirrororder(root);
printf("\n");
clear(root);
return 0;
}
神奇的二叉树
最新推荐文章于 2021-09-12 15:34:47 发布