二叉树先序构建+(先序,中序,后序遍历)

来源:互联网 发布:手机淘宝官方历史版本 编辑:程序博客网 时间:2024/06/17 15:22
/* * 样例     DBA,,C,,E,GF,,, */#include<cstdio>#include<cstdlib>#include<cmath>#include<map>#include<queue>#include<stack>#include<vector>#include<algorithm>#include<cstring>#include<string>#include<iostream>#define ms(x,y) memset(x,y,sizeof(x))const int MAXN=1000+10;const int INF=1<<30;using namespace std;struct Node{char ch;Node *left, *right;};void BuildTree(Node *&root){Node *s = (Node *)malloc(sizeof(Node));s->left = NULL;s->right = NULL;scanf("%c", &s->ch);if(s->ch == ','){free(s);return;}root = s;BuildTree(root->left);BuildTree(root->right);}void PreOrder(Node *root){if(root == NULL) return;printf("%c", root->ch);PreOrder(root->left);PreOrder(root->right);}void InOrder(Node *root){if(root == NULL) return;InOrder(root->left);printf("%c", root->ch);InOrder(root->right);}void PostOrder(Node *root){if(root == NULL) return;PostOrder(root->left);PostOrder(root->right);printf("%c", root->ch);}int main(){freopen("in.txt","r",stdin);Node *root;BuildTree(root);PreOrder(root);printf("\n");InOrder(root);printf("\n");PostOrder(root);printf("\n");return 0;}

1 0
原创粉丝点击