#include<iostream>
#include<string>
#include<vector>
#include<stack>
#include<queue>
using namespace std;
struct Node
{
int m_nValue;
Node* m_pLeft;
Node* m_pRight;
};
//符号分割函数
vector<string> split(const string &s, const string &seperator) {
vector<string> result;
typedef string::size_type string_size;
string_size i = 0;
while (i != s.size()) {
//找到字符串中首个不等于分隔符的字母;
int flag = 0;
while (i != s.size() && flag == 0) {
flag = 1;
for (string_size x = 0; x < seperator.size(); ++x)
if (s[i] == seperator[x]) {
++i;
flag = 0;
break;
}
}
//找到又一个分隔符,将两个分隔符之间的字符串取出;
flag = 0;
string_size j = i;
while (j != s.size() && flag == 0) {
for (string_size x = 0; x < seperator.size(); ++x)
if (s[j] == seperator[x]) {
flag = 1;
break;
}
if (flag == 0)
++j;
}
if (i != j) {
result.push_back(s.substr(i, j - i));
i = j;
}
}
return result;
}
//创建二叉树三连
Node* create_node(int value)
{
Node *new_node = new Node;
new_node->m_nValue = value;
new_node->m_pLeft = nullptr;
new_node->m_pRight = nullptr;
return new_node;
}
void ConnectTreeNodes(Node* pParent, Node* pLeft, Node* pRight)
{
if (pParent != nullptr)
{
pParent->m_pLeft = pLeft;
pParent->m_pRight = pRight;
}
}
//中序遍历
void in_order(Node*head)
{
stack<Node*> stack;
if (head == nullptr)
return;
Node *ptr = head;
Node *tmp = nullptr;
while (!stack.empty() || ptr != nullptr)
{
if (ptr != nullptr) {//注意 判断时不可以拿ptr->next做判断!
stack.push(ptr);
ptr = ptr->m_pLeft;
}
else {
tmp = stack.top();
cout << tmp->m_nValue << endl;
stack.pop();
ptr = tmp->m_pRight;
}
}
}
string SerialBinTree(Node* head)
{
if (head == nullptr)
return "#_";
string res = to_string(head->m_nValue) + "_";
res += SerialBinTree(head->m_pLeft);
res += SerialBinTree(head->m_pRight);
return res;
}
Node* ReConPreOrder(vector<string> s,int* i)
{
string value = s[i[0]];
if (value == "#") {
return nullptr;
}
Node* head = new Node;
head->m_nValue = atoi(value.c_str());
i[0]++;//这个i[0]是给下一Re用的
head->m_pLeft = ReConPreOrder(s, i);
i[0]++;//这个i[0]是给下一Re用的
head->m_pRight = ReConPreOrder(s, i);
return head;
}
Node* ReSerialBinTree(string s)
{
vector<string> s2 = split(s, "_");
int *index = new int[1];
index[0]=0;
return ReConPreOrder(s2,index);
}
int main()
{
Node* head = create_node(1);
Node* pNode2 = create_node(2);
Node* pNode3 = create_node(3);
Node* pNode4 = create_node(4);
Node* pNode5 = create_node(5);
Node* pNode6 = create_node(6);
Node* pNode7 = create_node(7);
Node* pNode8 = create_node(8);
Node* pNode9 = create_node(9);
Node* pNode10 = create_node(10);
Node* pNode11 = create_node(1);
ConnectTreeNodes(head, pNode2, pNode3);
ConnectTreeNodes(pNode2, pNode4, pNode5);
ConnectTreeNodes(pNode3, pNode6, pNode7);
ConnectTreeNodes(pNode5, pNode8, nullptr);
ConnectTreeNodes(pNode8, pNode9, nullptr);
in_order(head);
string str = SerialBinTree(head);
cout<<str<<endl;
Node* node= ReSerialBinTree(str);
in_order(node);
system("pause");
return 0;
}