#include <stdio.h>
#include <stdlib.h>
//二叉树结点
typedef struct BiTreeNode
{
int val;
struct BiTreeNode *lchild;
struct BiTreeNode *rchild;
}BiTreeNode, *BiTree;
//按先序序列构造二叉树
void createBiTree(BiTree &root)
{
char ch;
scanf("%c",&ch);
if (ch == '#')
{
root = NULL;
}
else
{
root = (BiTree)malloc(sizeof(BiTreeNode));
root->val = ch - 48;
printf("%d\n",root->val);
createBiTree(root->lchild);//构造左子树
createBiTree(root->rchild);//构造右子树
}
}
void visit(BiTree root)
{
printf("%d ",root->val);
}
//前序遍历
void preOrder(BiTree root)
{
if (root != NULL)
{
visit(root);//访问根结点
preOrder(root->lchild);
preOrder(root->rchild);
}
}
//中序遍历
void inOrder(BiTree root)
{
if (root != NULL)
{
inOrder(root->lchild);
visit(root);
inOrder(root->rchild);
}
}
//后序遍历
void postOrder(BiTree root)
{
if (root != NULL)
{
postOrder(root->lchild);
postOrder(root->rchild);
visit(root);
}
}
int main()
{
BiTree root;
createBiTree(root);
preOrder(root);
printf("\n");
inOrder(root);
printf("\n");
postOrder(root);
printf("\n");
return 0;
}
二叉树遍历
最新推荐文章于 2023-11-13 16:01:00 发布