树的存储结构
typedef struct BiNode
{
int data;
struct BiNode *left,*right;
}BiNode,* BiTree;
树的遍历
用以下二叉树作为例子,便于演示和理解。
![树的初始化](https://i-blog.csdnimg.cn/blog_migrate/ae40aa29c4c99800d69c557ff463fd15.png)
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;
}
前序遍历
前序遍历,就是先访问根节点,然后再访问左子树,最后访问右子树。如下图所示:
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/7c9e666e4627a67bf6fc21c20c02c93a.png)
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
中序遍历
中序遍历,就是先访问根节点,然后再访问左子树,最后访问右子树。
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/c5b145f5f2220ad5c8fe9dabf562b7ec.png)
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
后序遍历
后序遍历,就是先访问右子树,然后再访问根节点,最后访问右子树。
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/3424d7e5503db9eb9a96878a3c7fb86c.png)
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
三种遍历的作用