遍历二叉树
㈠先序遍历的操作定义如下:
若二叉树为空,则空操作,否则
①访问根结点
②先序遍历左子树
③先序遍历右子树
void preorder(tree bt) //先序遍历根结点为bt的二叉树的递归算法
{
if(bt)
{
cout << bt->data;
preorder(bt->lchild);
preorder(bt->rchild);
}
}
㈡中序遍历的操作定义如下:
若二叉树为空,则空操作,否则
①中序遍历左子树
②访问根结点
③中序遍历右子树
void inorder(tree bt) //中序遍历根结点为bt的二叉树的递归算法
{
if(bt)
{
inorder(bt->lchild);
cout << bt->data;
inorder(bt->rchild);
}
}
㈢后序遍历的操作定义如下:
若二叉树为空,则空操作,否则
①后序遍历左子树
②后序遍历右子树
③访问根结点
void postorder(tree bt) //后序遍历根结点为bt的二叉树的递归算法
{
if(bt)
{
postorder(bt->lchild);
postorder(bt->rchild);
cout << bt->data;
}
}
二叉树的其它重要操作
1、建立一棵二叉树
void pre_crt(tree &bt) //按先序次序输入二叉树中结点的值,生成
{
char ch;
ch = getchar(); //二叉树的单链表存储结构,bt为指向根结点的指针,'$'表示空树
if(ch != '$')
{
bt = new node; //建根结点
bt->data = ch;
pre_crt(bt->lchild); //建左子树
pre_crt(bt->rchild); //建右子树
}
else bt = NULL;
}
2、删除二叉树
void dis(tree &bt) //删除二叉树
{
if(bt)
{
dis(bt->lchild); //删左子树
dis(bt->rchild); //删右子树
delete bt; //释放父结点
}
}
3.插入一个结点到排序二叉树中
void insert(tree &bt, int n) //插入一个结点到排序二叉树中
{
if(bt)
{
if(n < bt->data) insert(bt->lchild, n);
else if(n > bt->data) insert(bt->rchild, n);
}
else
{
bt = new node; //新开一个空间
bt->data = n;
bt->lchild = bt->rchild = NULL;
}
}
6万+

被折叠的 条评论
为什么被折叠?



