C++实现二叉树先序遍历、中序遍历、后序遍历、利用先序遍历序列和中序遍历序列构造二叉树

#include <cstdio>
#include <string>
#include <iostream>
#include <stack>
using namespace std;
typedef struct BiTNode {
	char data;
	BiTNode* lchild = nullptr, * rchild = nullptr;
}*BiTree; //【BiTNode 二叉树结点】【BiTree 二叉树】
BiTree CreatBiTree(string preStr, string inStr) { //根据先序遍历序列和中序遍历序列构造二叉树
	BiTree temp = new BiTNode;
	temp->data = *(preStr.cbegin());
	size_t i;
	for (i = 0; i < inStr.size(); i++)
		if (inStr[i] == temp->data) break;
	string LpreStr, LinStr, RpreStr, RinStr;
	LpreStr = preStr.substr(1, i);
	LinStr = inStr.substr(0, i);
	RpreStr = preStr.substr(i + 1);
	RinStr = inStr.substr(i + 1);
	if (!LpreStr.empty())
		temp->lchild = CreatBiTree(LpreStr, LinStr);
	if (!RpreStr.empty())
		temp->rchild = CreatBiTree(RpreStr, RinStr);
	return temp;
}
string PreOrder(BiTree B) { //获取先序遍历序列
	if (B != nullptr) return B->data + PreOrder(B->lchild) + PreOrder(B->rchild);
	else return "";
}
string InOrder(BiTree B) { //获取中序遍历序列
	if (B != nullptr) return PreOrder(B->lchild) + B->data + PreOrder(B->rchild);
	else return "";
}
string InOrder2(BiTree B) {  //利用 栈 获取中序遍历序列
	string result;
	BiTNode* temp = B->lchild;
	stack<BiTNode*> st;	st.push(B);
	while (temp != nullptr) {
		st.push(temp);
		temp = temp->lchild;
	}
	while (!st.empty()) {
		temp = st.top(); st.pop();
		result += temp->data;
		temp = temp->rchild;
		if (temp != nullptr) {
			st.push(temp);
			temp = temp->lchild;
			while (temp != nullptr) {
				st.push(temp);
				temp = temp->lchild;
			}
		}
	}
	return result;
}
string PostOrder(BiTree B) {  //获取后序遍历序列
	if (B != nullptr) return PreOrder(B->lchild) + PreOrder(B->rchild) + B->data;
	else return "";
}
int main()
{
	string pre("ABDGCEF"), in("DGBAECF");
	auto MyBiTree = CreatBiTree(pre, in);
	cout << InOrder2(MyBiTree) << endl;
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值