先序扩展序列建立二叉树;先序、中序、后序遍历的递归算法(树)
#include<stdio.h> #include<stdlib.h> typedef struct BinNode{ char element; struct BinNode *left; struct BinNode *right; }BinNode,*BinTree; void CreateBinTree(BinTree *tree){ char ch; scanf("%c",&ch); if(ch == '.'){ (*tree) = NULL; } else{ if(!(*tree = (BinTree)malloc(sizeof(BinNode)))){ exit(-1); } (*tree)->element = ch; CreateBinTree(&((*tree)->left)); CreateBinTree(&((*tree)->right)); } } void Preorder(BinTree T){ if(T){ printf("%c",T->element); Preorder(T->left); Preorder(T->right); } } void Inorder(BinTree T){ if(T){ Inorder(T->left); printf("%c",T->element); Inorder(T->right); } } void Postorder(BinTree T){ if(T){ Postorder(T->left); Postorder(T->right); printf("%c",T->element); } } int main(){ BinTree T = NULL; printf("请输入您要建立的二叉树的先序扩展序列(用.表示空)\n"); CreateBinTree(&T); printf("构造二叉树成功!\n"); printf("先序遍历:"); Preorder(T); printf("\n中序遍历:"); Inorder(T); printf("\n后序遍历:"); Postorder(T); printf("\n"); }
测试数据:
124.6…3.5.7.8..
测试答案:
先序遍历:12463578
中序遍历:46213578
后序遍历:64287531
124..5..36..7..