二叉树前中后序遍历cpp
title
#include <cstdio>
#include <cstring>
#include <iostream>
using namespace std;
/*
前序 HGEDBFCA, 中序 EGBD H FAC, 后序 EBDGACFH,
root : H
left : EGBD
root : FAC
*/
void reqBackOrder(string middle, string front) {
if (middle.size() > 0) {
char root = front[0];
int k = middle.find(root);
reqBackOrder(middle.substr(0, k), front.substr(1, k)); // left
reqBackOrder(middle.substr(k + 1), front.substr(k + 1, middle.size() - k - 1));
cout << root;
}
}
void reqFrontOrder(string middle, string after) {
if (middle.size() > 0) {
char root = after[after.size() - 1];
cout << root;
int k = middle.find(root);
reqFrontOrder(middle.substr(0, k), after.substr(0, k));
reqFrontOrder(middle.substr(k + 1), after.substr(k, middle.size() - k - 1));
}
}
int main(int argc, char *argv[]) {
char flag;
if (argc != 2) {
cout << "need arg: 0 or 1 indicate front or back" << endl;
return 0;
}
flag = argv[1][0];
string middle;
if ('0' == flag) {
string front;
cout << "input front order string" << endl;
cin >> front;
cout << "input middle order string" << endl;
cin >> middle;
cout << "back order string:";
reqBackOrder(middle, front);
} else {
string back;
cout << "input middle order string" << endl;
cin >> middle;
cout << "input middle back string" << endl;
cin >> back;
cout << "front order string:";
reqFrontOrder(middle, back);
}
cout << endl;
return 0;
}