题解 | #二叉树遍历#
二叉树遍历
https://www.nowcoder.com/practice/6e732a9632bc4d12b442469aed7fe9ce
#include<stdio.h>
#include<string.h>
#include<malloc.h>
typedef struct tree {
struct tree *left;
struct tree *right;
char data;
}t;
int find(char a,char *b) {
int i=0;
while(b[i]!=a) {
i=i+1; }
return i;
}
void write(t *tree) {
if(tree->left!=NULL) {
write(tree->left);
}
if(tree->right!=NULL) {
write(tree->right);
}
printf("%c",tree->data);
}
void spy(char *str,int i,int j,char *a) {
int k;
for (k = 0; k < j - i + 1; k++) {
a[k] = str[k + i];
}
a[k] = '\0';
}
t* get(char* str1, char* str2) {
t* tr;
char* str11, *str22;
str11 = (char*)malloc(100 * sizeof(char));
str22 = (char*)malloc(100 * sizeof(char));
int d;
tr = (t*)malloc(sizeof(t));
tr->data = str1[0];
tr->left = NULL;
tr->right = NULL;
d = find(str1[0], str2);
if (d >= 0) {
if (d > 0) {
spy(str1, 1, d, str11);
spy(str2, 0, d - 1, str22);
tr->left = get(str11, str22);
}
if (d < strlen(str1) - 1) {
spy(str1, d + 1, strlen(str1) - 1, str11);
spy(str2, d + 1, strlen(str2) - 1, str22);
tr->right = get(str11, str22);
}
}
return tr;
}
int main() {
int i, n;
char a[26], b[26];
while(scanf("%s %s",&a,&b)!=EOF){
t* tr;
tr = get(a, b);
write(tr);
printf("\n");
}
}
查看16道真题和解析
