二叉树的遍历(c++)

#include "stdafx.h"
#include <iostream>

using namespace std;

struct BiNode
{
	char data;
	BiNode *lchild, *rchild;
};


BiNode *inorder_create()   //中序遍历建立二叉树
{
	BiNode *bt;
	char ch;
	cin.get(ch);
	if (ch == '\n') bt=NULL;
	else
	{
		bt = (BiNode*)malloc(sizeof(BiNode));
		bt->data = ch;
		bt->lchild = inorder_create();
		bt->rchild = inorder_create();
	}
	return bt;
}

void Release(BiNode *bt)       //后序遍历销毁树
{
	if (bt == NULL) return;                 //递归调用的结束条件
	else
	{
		Release(bt->lchild);               //后序递归遍历bt的左子树
		Release(bt->rchild);               //后序递归遍历bt的右子树
		free(bt);                        //销毁根结点bt
	}
}

void visit(char data)    //输出数据域
{
	cout << data;
}

void PostOrder(BiNode *bt)             //后序递归遍历树
{
	if (bt == NULL) return;                //递归调用的结束条件
	else
	{
		PostOrder(bt->lchild);             //后序递归遍历bt的左子树
		PostOrder(bt->rchild);             //后序递归遍历bt的右子树
		visit(bt->data);                   //访问根结点bt的数据域
	}
}

void preorder(BiNode *bt)
{
	if (bt == NULL) return;
	else
	{
		visit(bt->data);
		preorder(bt->lchild);
		preorder(bt->rchild);
	}
}

void inorder(BiNode *bt)   //中序遍历
{
	if (bt == NULL) return;
	else
	{
		inorder(bt->lchild);
		visit(bt->data);
		inorder(bt->rchild);
	}
}
void Leverorder(BiNode *bt) //借助由数组(20)组成的循环队列实现按层遍历树
{
	int front = 0, rear = 0;
	BiNode *Q[20], *q;
	if (bt == NULL) return;
	Q[rear] = bt;
	rear = (rear + 1) % 20;
	while (front != rear)
	{
		q = Q[front];
		cout << q->data;      //出队
		front = (front + 1) % 20;
		if (q->lchild != NULL) Q[rear] = q->lchild, rear = (rear + 1) % 20;  //左子树入队
		if (q->rchild != NULL) Q[rear] = q->rchild, rear = (rear + 1) % 20;  //右子树入队
	}

}
void main()
{
	BiNode *bt = inorder_create();
	cout <<endl<< "后序遍历:" ;
	PostOrder(bt);
	cout << endl<<"先序遍历:" ;
	preorder(bt);
	cout <<endl<< "中序遍历:" ;
	inorder(bt);
	cout << endl << "按层遍历:";
	Leverorder(bt);
	Release(bt);
	system("pause");
}

猜你喜欢

转载自blog.csdn.net/weixin_41338006/article/details/79151129