数据结构上机测试4.1:二叉树的遍历与应用1
View Code
#include <stdio.h> #include <stdlib.h> #include <string.h> #define MAXN 200 void build(int n, char *s1, char *s2, char *s){ if(n<=0) return; int p = strchr(s2, s1[0]) - s2; build(p, s1+1, s2, s); build(n-p-1, s1+p+1, s2+p+1, s+p); s[n-1] = s1[0]; } int main(){ char s1[MAXN], s2[MAXN], s[MAXN]; scanf("%s %s", s1, s2); int len = strlen(s1); build(len, s1, s2, s); s[len] = '\0'; printf("%s", s); return 0; }
数据结构实验之二叉树的建立与遍历
View Code
#include <stdio.h> #include <stdlib.h> typedef int ElemType; typedef int Status; typedef struct Node{ ElemType data; struct Node *lchild, *rchild; }Node, *Tree; Status create_tree(Tree *T){ char ch = getchar(); if(ch == ',') (*T)=NULL; else{ (*T) = (Tree)malloc(sizeof(Node)); if(!(*T)) return 0; (*T)->data = ch; create_tree(&(*T)->lchild); create_tree(&(*T)->rchild); } return 1; } void print_in(Tree T){ if(T){ print_in(T->lchild); putchar(T->data); print_in(T->rchild); } } void print_la(Tree T){ if(T){ print_la(T->lchild); print_la(T->rchild); putchar(T->data); } } int cnt_depth(Tree T){ if(!T) return 0; int a, b; a = cnt_depth(T->lchild); b = cnt_depth(T->rchild); if(a>b) return a+1; else return b+1; } int cnt_leaf(Tree T){ if(!T->lchild && !T->rchild) return 1; else{ if(!T->lchild) return cnt_leaf(T->rchild); if(!T->rchild) return cnt_leaf(T->lchild); else return cnt_leaf(T->lchild)+cnt_leaf(T->rchild); } } int main(){ Tree T; create_tree(&T); print_in(T); putchar('\n'); print_la(T); putchar('\n'); printf("%d\n", cnt_leaf(T)); printf("%d\n", cnt_depth(T)); return 0; }
数据结构实验之求二叉树后序遍历和层次遍历
View Code
#include <stdio.h> #include <stdlib.h> #include <string.h> #define MAXN 200 typedef int ElemType; typedef int Status; typedef struct Node{ ElemType data; struct Node *lchild, *rchild; }Node, *Tree; Tree q[MAXN]; void build(Tree *T, char *s1, char *s2, int len){ if(len <= 0) {(*T) = NULL; return ;} (*T) = (Tree)malloc(sizeof(Node)); int p = strchr(s2, s1[0]) - s2; (*T)->data = s1[0]; build(&(*T)->lchild, s1+1, s2, p); build(&(*T)->rchild, s1+p+1, s2+p+1, len-p-1); } void print_la(Tree T){ if(T){ print_la(T->lchild); print_la(T->rchild); putchar(T->data); } } void BFS(Tree T){ int front, rear; Tree bt; front = rear = 0; if(T) q[rear++] = T; while(front<rear){ bt = q[front++]; putchar(bt->data); if(bt->lchild) q[rear++] = bt->lchild; if(bt->rchild) q[rear++] = bt->rchild; } } int main(){ Tree T; int t; char s1[MAXN], s2[MAXN]; scanf("%d", &t); while(t--){ scanf("%s %s", s1, s2); int len = strlen(s1); build(&T, s1, s2, len); print_la(T); putchar('\n'); BFS(T); putchar('\n'); } return 0; }