根据二叉树前序中序输出后续遍历
+前中后三种遍历的递归与非递归解法
+广度优先遍历
#include<iostream>
#include<cstring>
#include<stack>
#include<vector>
#include<queue>
using namespace std;
struct node
{
char value;
node* left;
node* right;
};
node* rebuildTree(char *pre, char *mid) {
int length = strlen(pre);
if (length == 0) {
return NULL;
}
node* root = new node();
root->value = pre[0];
char* mleft=new char[100], *mright=new char[100];
char* pleft = new char[100], *pright = new char[100];
bool flag = 1;
int k = 0, s = 0;
for (int i = 0; i < length; i++) {
if (mid[i] == pre[0]) {
flag = 0;
}
else {
if (flag) {
mleft[k++] = mid[i];
}
else {
mright[s++] = mid[i];
}
}
}
mleft[k] = '\0';
mright[s] = '\0';
int q = 0, w = 0;
for (int i = 1; i < length; i++) {
if (q < k) {
pleft[q++] = pre[i];
}
else {
pright[w++] = pre[i];
}
}
pleft[q] = '\0';
pright[w] = '\0';
root->left = rebuildTree(pleft, mleft);
root->right = rebuildTree(pright, mright);
return root;
}
void post_order(node* root) {
if (root != NULL) {
post_order(root->left);
post_order(root->right);
cout << root->value << " ";
}
}
void post_nonR1(node* root) {
stack<node*> s1, s2;
node* tmp = root;
s1.push(tmp);
while (!s1.empty()) {
tmp = s1.top();
s1.pop();
s2.push(tmp);
if (tmp->left != NULL) {
s1.push(tmp->left);
}
if (tmp->right != NULL) {
s1.push(tmp->right);
}
}
while (!s2.empty()) {
tmp = s2.top();
cout << tmp->value << " ";
s2.pop();
}
cout << endl;
}
void pre_order(node* root) {
if (root != NULL) {
cout << root->value << " ";
pre_order(root->left);
pre_order(root->right);
}
}
void pre_nonR(node *root) {
stack<node*> s;
if (root == NULL) return;
s.push(root);
while (!s.empty())
{
node *p = s.top();
s.pop();
cout << p->value << " ";
if (p->right != NULL) {
s.push(p->right);
}
if (p->left != NULL) {
s.push(p->left);
}
}
cout << endl;
}
void mid_nonR(node *root) {
stack<node*> s;
if (root == NULL) return;
node* tmp = root;
while (!s.empty()||tmp!=NULL)
{
if (tmp == NULL) {
tmp = s.top();
s.pop();
cout << tmp->value << " ";
tmp = tmp->right;
}
else {
s.push(tmp);
tmp = tmp->left;
}
}
cout << endl;
}
void mid_order(node* root) {
if (root != NULL) {
mid_order(root->left);
cout << root->value << " ";
mid_order(root->right);
}
}
void bfs(node *root) {
queue<node*> q;
node* tmp = root;
q.push(tmp);
while (!q.empty())
{
tmp = q.front();
cout << tmp->value << " ";
q.pop();
if (tmp->left != NULL) {
q.push(tmp->left);
}
if (tmp->right != NULL) {
q.push(tmp->right);
}
}
cout << endl;
}
int main() {
char *pre = "12473568", *mid = "47215368";
node* root = rebuildTree(pre, mid);
pre_order(root);
cout << endl;
pre_nonR(root);
cout << endl;
mid_order(root);
cout << endl;
mid_nonR(root);
cout << endl;
post_order(root);
cout << endl;
post_nonR1(root);
cout << endl;
bfs(root);
}