1, the first sequence traversal: First order traversal is the first output root node, and then output the left subtree, and finally output the right subtree. The result of the first order traversal is: ABCDEF
2, the middle sequence traversal: the middle sequence traversal is the first output of the left subtree, and then output the root node, and finally output the right sub-tree. The result of the middle sequence traversal is: CBDAEF
3, after the post-traversal: The post-traversal is the first output of the left subtree, and then output the right subtree, the final output root node. The result of the post-sequential traversal is: CDBFEA
|
#include <stdio.h>
#include <stdlib.h>
typedef
char TelemType;
typedef
struct TNode{
TelemType data;
struct
TNode *lchild,*rchild;
} BitNode;
//声明
BitNode* createTree(
void
);
void
preOrderTraverse(BitNode *);
void
inOrderTraverse(BitNode *);
void
lastOrderTraverse(BitNode *);
int main(
int agrc,
char
*argv[]){
BitNode *root=NULL;
root=createTree();
printf
(
"\n先序遍历二叉树:"
);
preOrderTraverse(root);
printf
(
"\n中序遍历二叉树:"
);
inOrderTraverse(root);
printf
(
"\n后序遍历二叉树:"
);
lastOrderTraverse(root);
return
0;
}
//创建二叉树
BitNode* createTree(
void
){
BitNode *b;
TelemType ch;
scanf
(
"%c"
,&ch);
if
(ch==
‘#‘
){
b=NULL;
}
else
{
b=(BitNode *)
malloc
(
sizeof
(BitNode))
b->data=ch;
b->lchild=createTree();
b->rchild=createTree();
}
return
b;
}
//先序遍历
void
preOrderTraverse(BitNode *root){
if
(root){
printf
(
"%c"
,root->data);
preOrderTraverse(root->lchild);
preOrderTraverse(root->rchild);
}
}
//中序遍历
void
inOrderTraverse(BitNode *root){
if
(root){
inOrderTraverse(root->lchild);
printf
(
"%c"
,root->data);
inOrderTraverse(root->rchild);
}
}
//后序遍历
void
lastOrderTraverse(BitNode *root){
if
(root){
lastOrderTraverse(root->lchild);
lastOrderTraverse(root->rchild);
printf
(
"%c"
,root->data);
}
}
|
Results:
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Three kinds of traversal of binary tree