The realization of pre-order, middle-order and post-order traversal of binary tree

First-order traversal
if the binary tree is empty, no operation; otherwise
1. Visit the root node
2. First-order traverse the left sub-tree
3. First-order traverse the right sub-tree

Middle-order traversal
if the binary tree is empty, then no operation; otherwise
1. Middle-order traversal of the left subtree
2. Access to the root node
3. Middle-order traversal of the right subtree

Post-order traversal
if the binary tree is empty, no operation; otherwise
1. Post-order traversal of the left sub-tree
2. Post-order traversal of the right sub-tree
3. Visit the root node

Recursively implement the traversal of the binary tree:

#include <bits/stdc++.h>
using namespace std;
typedef char TElemType;
typedef int Status;
//用二叉链表存储表示二叉树
typedef struct BiTNode{
    
    
	TElemType data;
	struct BiTNode *lchild, *rchild;
}*BiTree, BiTNode;

//构造空二叉树
void InitBiTree(BiTree T)
{
    
    
	T=(BiTree)malloc(sizeof(BiTNode));
	if(!(T)) exit(OVERFLOW);
	T->lchild=NULL;
	T->rchild=NULL;
	return ;
}
//前序遍历二叉树
void CreateBiTreePreOrder(BiTree &T){
    
    
    TElemType ch;
	ch = getchar();
	getchar();
	if(ch =='#'){
    
    
        T = NULL;
	}
    else{
    
    
        T= (BiTree)malloc(sizeof(BiTNode));
        if(!T) exit(OVERFLOW);
		T->data = ch;
		CreateBiTreePreOrder(T->lchild);
		CreateBiTreePreOrder(T->rchild);
	}
}
//递归的先序遍历
void PreOrder(BiTree T){
    
    
	if(T){
    
    
		cout<<T->data<<" ";
		PreOrder(T->lchild);
		PreOrder(T->rchild);
	}
}
//递归的中序遍历
void InOrder(BiTree T){
    
    
	if(T){
    
    
        InOrder(T->lchild);
		cout<<T->data<<" ";
		InOrder(T->rchild);
	}
}
//递归的后序遍历 
void PostOrder(BiTree T){
    
    
	if(T){
    
    
        PostOrder(T->lchild);
		cout<<T->data<<" ";
		PostOrder(T->rchild);
	}
}
int main()
{
    
    
    BiTree T;
    InitBiTree(T);
    CreateBiTreePreOrder(T);
    cout<<"前序遍历为:"<<endl;
    PreOrder(T);
    cout<<endl;
    cout<<"中序遍历为:"<<endl;
    InOrder(T);
    cout<<endl;
    cout<<"后序遍历为:"<<endl;
    PostOrder(T);
    return 0;
}

Insert picture description here

Guess you like

Origin blog.csdn.net/qq_43811879/article/details/110311818