已知二叉樹的一個按先序遍歷輸入的字符序列,如abc,,de,g,,f,,, (其中,表示空結點)。請建立二叉樹并按中序和后序的方式遍歷該二叉樹。 Input
連續輸入多組數據,每組數據輸入一個長度小于50個字符的字符串。 Output
每組輸入數據對應輸出2行: 第1行輸出中序遍歷序列; 第2行輸出后序遍歷序列。
Example Input
abc,,de,g,,f,,,Example Output
cbegdfacgefdbaHint
Author xam
#include <iostream>#include <stdio.h>#include <stdlib.h>#include <string.h>using namespace std;typedef struct node{ char a; node *left; node *right;}Node;int top=0;struct node *creat(char *p)//建樹方法{ Node *root=NULL; if(top<strlen(p)) { if(p[top]!=',') { root=(Node *)malloc(sizeof(Node)); root->left=NULL; root->right=NULL; root->a=p[top++]; root->left=creat(p); root->right=creat(p); } else { top++; } } return root;}void zhong(Node *root)//中序遍歷,先序和后序類似{ if(root) { zhong(root->left); printf("%c", root->a); zhong(root->right); }}void hou(Node *root){ if(root) { hou(root->left); hou(root->right); printf("%c", root->a); }}int main(){ char p[60]; while(~scanf("%s", p)) { Node *root; top=0; root = creat(p); zhong(root); printf("/n"); hou(root); printf("/n"); }}新聞熱點
疑難解答