#include <iostream> #include <cstdio> #include <malloc.h> using namespace std; typedef struct tree{ char a; tree *lchild; tree *rchild; }; tree* create(tree *T){ char c=getchar(); if(c==‘#‘){ T=NULL; }else{ T=(tree*)malloc(sizeof(tree)); T->a=c; if(!T){ printf("\Error!n"); } T->lchild=create(T->lchild); T->rchild=create(T->rchild); } return T; } void preorder(tree *T){ if(T){ printf("%c",T->a); preorder(T->lchild); preorder(T->rchild); } } void inorder(tree *T){ if(T){ inorder(T->lchild); printf("%c",T->a); inorder(T->rchild); } } void postorder(tree *T){ if(T){ postorder(T->lchild); postorder(T->rchild); printf("%c",T->a); } } //非递归先序遍历 //非递归中序遍历 int main() { tree *T; printf("Plese input the tree‘s sequence:\n"); T=create(T); printf("preorder: "); preorder(T); printf("\n"); printf("inorder: "); inorder(T); printf("\n"); printf("postorder: "); postorder(T); printf("\n"); return 0; }
时间: 2024-10-27 17:38:56