二叉树的遍历
- 先序遍历:根左右,最左边为根节点
- 中序遍历:左根右,中间为根节点,根节点左边为左子树,右边为右子树 c.
- 后序遍历:左右根,最右边为根节点
代码实现【递归】
/*先序遍历*/
void PreOrder(BiTree T)
{
if (T != NULL)
{
visit(T); // 访问结点
PreOrder(T->lchild); // 遍历结点左子树
PreOrder(T->rchild); // 遍历结点右子树
}}
/*中序遍历*/
void InOrder(BiTree T)
{
if (T != NULL)
{
InOrder(T->lchild); // 遍历结点左子树
visit(T); // 访问结点
InOrder(T->rchild); // 遍历结点右子树
}}
/*后序遍历*/
void PostOrder(BiTree T)
{
if (T != NULL)
{
PostOrder(T->lchild); // 遍历结点左子树
PostOrder(T->rchild); // 遍历结点右子树
visit(T); // 访问结点
}}
/*输出树结点*/
void visit(BiTree T)
{
printf("树结点的值:%c\n", T->data);
}
(先序+中序)或(中序+后序)都可以唯一确定一个二叉树
已知中序和后序,求出二叉树,下面是代码实现
template <class ElemType>
void CreateBinaryTreeHelp_PostIn(BinTreeNode<ElemType> *&r, ElemType post[], ElemType in[],
int postLeft, int postRight, int inLeft, int inRight)
// 操作结果:已知二叉树的后序序列post[postLeft..postRight]和中序序列in[inLeft..inRight]构造
// 以r为根的二叉树
{
if (postLeft > postRight || inLeft > inRight)
{
r = NULL;
}
else
{
r = new BinTreeNode<ElemType>(post[postRight]); //后序遍历的最后一个结点即为根节点
int mid = inLeft; //设置Mid用来存储在中序遍历中根节点r的位置
while (in[mid] != post[postRight])
{
mid++;
}
CreateBinaryTreeHelp(r->leftChild, post, in, postLeft, postLeft + inRight - mid, inLeft, mid - 1); //递归构造左子树
CreateBinaryTreeHelp(r->rightChild, post, in, postLeft + mid - inLeft, postRight - 1, mid + 1, inRight); //递归构造右子树
}
}
template <class ElemType>
BinaryTree<ElemType> CreateBinaryTree_PostIn(ElemType post[], ElemType in[], int n)
// 操作结果:已知后序和中序序列构造二叉树
{
BinTreeNode<ElemType> *r; // 二叉树的根
CreateBinaryTreeHelp_PostIn<ElemType>(r, post, in, 0, n - 1, 0, n - 1);
return BinaryTree<ElemType>(r); // 返回以r为根的二叉树
}
4. 二叉树与森林的相互转换