代码中创建的二叉树如下图
013##4##25##6##
代码:
#include <stdio.h>
#include <stdlib.h>
typedef struct Tree{
int value;
struct Tree* lchild;
struct Tree* rchild;
} Tree;
// 创建节点
Tree* Tree_createnode(int value){
Tree* node = (Tree* )malloc(sizeof(Tree));
node->value = value;
node->lchild = NULL;
node->rchild = NULL;
return node;
}
// 创建二叉树
Tree* Tree_createtree(){
Tree* root = NULL;
char ch;
scanf("%c", &ch);
if(ch == '#') return root;
else{
root = Tree_createnode(ch - '0');
root->lchild = Tree_createtree();
root->rchild = Tree_createtree();
}
return root;
}
// 前序遍历
void Tree_preorder(Tree* root){
if(root != NULL){
printf("[%d] -> ", root->value);
Tree_preorder(root->lchild);
Tree_preorder(root->rchild);
}
}
// 中序遍历
void Tree_inorder(Tree* root){
if(root != NULL){
Tree_inorder(root->lchild);
printf("[%d] -> ", root->value);
Tree_inorder(root->rchild);
}
}
// 后序遍历
void Tree_postorder(Tree* root){
if(root != NULL){
Tree_postorder(root->lchild);
Tree_postorder(root->rchild);
printf("[%d] -> ", root->value);
}
}
int main(){
printf("创建二叉树:\n");
Tree* root = Tree_createtree();
printf("前序遍历二叉树:\n");
Tree_preorder(root);
printf("NULL\n");
printf("中序遍历二叉树:\n");
Tree_inorder(root);
printf("NULL\n");
printf("后续遍历二叉树:\n");
Tree_postorder(root);
printf("NULL\n");
return 0;
}
这三种遍历如何区分?其实是按头节点的打印顺序,前序遍历即头结点先被打印,中序遍历次之,后续遍历即最后打印头结点