c++二叉树的建立和遍历

有错误大家可以指出来,本文主要是中对二叉树的先序、中序和后序非递归遍历进行编写,代码如下:

#include
#include
using namespace std;
//定义节点
typedef struct node
{
	struct node *lchild;
	struct node *rchild;
	char data;
	node(char data) :
		data(data), lchild(nullptr), rchild(nullptr) {}
}BiTreeNode, *BiTree; 

//按照前序顺序建立二叉树
void createBiTree(BiTree &T) 
{
	char c;
	cin >> c;
	if ('#' == c)             
		T = nullptr;
	else
	{
		T = new BiTreeNode(c);
		createBiTree(T->lchild);
		createBiTree(T->rchild);
	}
}

//前序遍历二叉树并打印
void preTraverse(BiTree T)
{
	if (T)
	{
		cout << T->data << " ";
		preTraverse(T->lchild);
		preTraverse(T->rchild);
	}
}
//中序遍历二叉树并打印
void midTraverse(BiTree T)
{
	if (T)
	{
		midTraverse(T->lchild);
		cout << T->data << " ";
		midTraverse(T->rchild);
	}
}
//后续遍历二叉树并打印
void postTraverse(BiTree T)
{
	if (T)
	{
		postTraverse(T->lchild);
		postTraverse(T->rchild);
		cout << T->data << " ";
	}
}
void  preOrderUnRecur(BiTree T) {
	if (T == nullptr)
		return;
	stack<BiTree> s;
	s.push(T);
	while (!s.empty()) {
		BiTree T = s.top();
		cout << T->data << ",";
		s.pop();
		if (T->rchild != nullptr) {
			s.push(T->rchild);
		}
		if (T->lchild != nullptr) {
			s.push(T->lchild);
		}
	}
}
void inOrderUnRecur(BiTree T) {
	if (T == nullptr)
		return;
	stack<BiTree> s;
	while (T || !s.empty()) {
		if (T) {
			s.push(T);
			T = T->lchild;
		}
		else {
			T = s.top();
			cout << T->data << ",";
			s.pop();
			T = T->rchild;
		}
	}
}
void postOrderUnRecr(BiTree T) {
	if (!T)
		return;
	stack<BiTree> s1, s2;
	s1.push(T);
	while (!s1.empty()) {
		BiTree T = s1.top();
		s2.push(T);
		s1.pop();
		if (T->lchild)
			s1.push(T->lchild);
		if (T->rchild)
			s1.push(T->rchild);
	}
	while (!s2.empty()) {
		cout << s2.top()->data << ",";
		s2.pop();
	}
}
int main()
{
	BiTree T;               //声明一个指向二叉树根节点的指针               
	createBiTree(T);
	cout << "二叉树创建完成!" << endl;
	cout << "前序遍历二叉树:" << endl;
	preTraverse(T);
	cout << endl;
	preOrderUnRecur(T);
	cout << endl;
	cout << "中序遍历二叉树:" << endl;
	midTraverse(T);
	cout << endl;
	inOrderUnRecur(T);
	cout << endl;
	cout << "后序遍历二叉树:" << endl;
	postTraverse(T);
	cout << endl;
	postOrderUnRecr(T);
	cout << endl;
	return 0;
}

c++二叉树的建立和遍历_第1张图片

你可能感兴趣的:(c++,c++,二叉树,数据结构)