typedef struct TreeNode{
struct TreeNode *left;
struct TreeNode *right;
char val;
}BiTreeNode, *binTree;
// 按照前序遍历的方式输入,遇到没有左孩子和右孩子用空格代替
void createTree_(binTree *root){
char input;
scanf("%c", &input);
if (input == ' ') {
root = NULL;
return;
}
*root = (struct TreeNode *)malloc(sizeof(struct TreeNode));
(*root)->val = input;
createTree_(&(*root)->left);
createTree_(&(*root)->right);
}
// 前序遍历
void PreOrderTraversalBinTree(BiTreeNode *root){
if (root == NULL) { return; }
printf("%c", root->val);
PreOrderTraversalBinTree(root->left);
PreOrderTraversalBinTree(root->right);
}
// 中序遍历
void InOrderTraversalBinTree(BiTreeNode *root){
if (root == NULL) { return; }
InOrderTraversalBinTree(root->left);
printf("%c", root->val);
InOrderTraversalBinTree(root->right);
}
//后序遍历
void TailOrderTraversalBinTree(BiTreeNode *root){
if (root == NULL) { return; }
TailOrderTraversalBinTree(root->left);
TailOrderTraversalBinTree(root->right);
printf("%c", root->val);
}
+ (void)test{
printf("请按照前序遍历方式输入二叉树:");
binTree root = NULL;
createTree_(&root);
printf("二叉树前序遍历的结果:");
PreOrderTraversalBinTree(root);
putchar('\n');
printf("二叉树中序遍历的结果:");
InOrderTraversalBinTree(root);
putchar('\n');
printf("二叉树后序遍历的结果:");
TailOrderTraversalBinTree(root);
putchar('\n');
}
网友评论