已知某一二叉树的先序遍历为:136945827,中序遍历为:963548127,求此二叉树的后续遍历
#include<iostream>
#include<string>
using std::cout;
using std::endl;
using std::string;
class Node {
public:
int data;
Node *lchild, *rchild;
Node(int _data) {
data = _data;
lchild = NULL;
rchild = NULL;
}
~Node() {
if (lchild != NULL) {
delete lchild;
}
if (rchild != NULL) {
delete rchild;
}
}
void postorder() {
if (lchild != NULL) {
lchild->postorder();
}
if (rchild != NULL) {
rchild->postorder();
}
cout << data << " ";
}
// 传入先序遍历的字符串,中序遍历的字符串,和字符串长度
Node* build(const string & pre_str, const string & in_str, int len) {
//先序遍历字符串的第一个字符为根节点
Node * p = new Node(pre_str[0] - '0');
//通过根节点在中序遍历字符串中的位置,可以得知此位置往左的为左树,往右的为右数
int pos = in_str.find(pre_str[0]);
//判断是否右左树
if (pos > 0) {
// 如果有左树的话,便递归调用此方法,生成左树
p->lchild = build(pre_str.substr(1, pos), in_str.substr(0, pos), pos);
}
//判断是否有右树
if (len - pos - 1 > 0) {
// 如果有右树的话,便递归调用此方法,生成右树
p->rchild = build(pre_str.substr(pos + 1), in_str.substr(pos + 1), len - pos - 1);
}
return p;
}
};
class BinaryTree {
private:
Node *root;
public:
BinaryTree() {
root = NULL;
}
~BinaryTree() {
delete root;
}
BinaryTree(const string & pre_str, const string & in_str, int len) {
root = root->build(pre_str, in_str, len);
}
void postorder() {
root->postorder();
}
};
int main() {
string pre_str = "136945827";
string in_str = "963548127";
BinaryTree binarytree(pre_str, in_str, in_str.length());
binarytree.postorder();
cout << endl;
return 0;
}