树的存储结构
typedef struct BiNode
{
int data;
struct BiNode *left,*right;
}BiNode,* BiTree;
树的遍历
用以下二叉树作为例子,便于演示和理解。

void InitTree(BiTree &root)
{
root=(BiTree)malloc(sizeof(BiNode));
root->left=(BiNode *)malloc(sizeof(BiNode));
root->right=(BiNode *)malloc(sizeof(BiNode));
root->data=1;
root->left->data=2;
root->right->data=3;
root->left->left=(BiNode *)malloc(sizeof(BiNode));
root->left->right=(BiNode *)malloc(sizeof(BiNode));
root->left->left->data=4;
root->left->right->data=5;
root->left->right->left=NULL;
root->left->right->right=NULL;
root->right->left=(BiNode *)malloc(sizeof(BiNode));
root->right->right=NULL;
root->right->left->data=6;
root->right->left->left=NULL;
root->right->left->right=NULL;
root->left->left->left=NULL;
root->left->left->right=(BiNode *)malloc(sizeof(BiNode));
root->left->left->right->data=7;
root->left->left->right->left=NULL;
root->left->left->right->right=NULL;
}
前序遍历
前序遍历,就是先访问根节点,然后再访问左子树,最后访问右子树。如下图所示:

bool PreOrder(BiTree tree)
{
if(tree==NULL) return false;
visit(tree);
PreOrder(tree->left);
PreOrder(tree->right);
return true;
}
BiTree tree;
InitTree(tree);
printf("前序遍历:");
PreOrder(tree);
前序遍历:1->2->4->7->5->3->6
中序遍历
中序遍历,就是先访问根节点,然后再访问左子树,最后访问右子树。

bool InOrder(BiTree tree)
{
if(tree==NULL) return false;
InOrder(tree->left);
visit(tree);
InOrder(tree->right);
return true;
}
BiTree tree;
InitTree(tree);
printf("\n中序遍历:");
InOrder(tree);
中序遍历:4->7->2->5->1->6->3
后序遍历
后序遍历,就是先访问右子树,然后再访问根节点,最后访问右子树。

bool PostOrder(BiTree tree)
{
if(tree==NULL) return false;
PostOrder(tree->left);
PostOrder(tree->right);
visit(tree);
return true;
}
代码
bool visit(BiTree tree)
{
printf("%d->",tree->data);
return true;
}
BiTree tree;
InitTree(tree);
printf("\n后序遍历:");
PostOrder(tree);
后序遍历:7->4->5->2->6->3->1
三种遍历的作用