#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;
}
C++实现二叉树先序遍历、中序遍历、后序遍历、利用先序遍历序列和中序遍历序列构造二叉树
最新推荐文章于 2022-05-29 21:13:05 发布