结果输出
#include<iostream>
using namespace std;
struct Node {
public:
char data;
Node* left;
Node* right;
Node() {
left = NULL;
right = NULL;
}
Node(char ch, Node* left, Node* right) {
this->data = ch;
this->left = left;
this->right = right;
}
};
//二叉树的前序遍历
void preOrder(Node* root) {
if (root == NULL) {
return;
}
cout << root->data << " ";
preOrder(root->left);
preOrder(root->right);
}
//二叉树的中序遍历
void midOrder(Node* root) {
if (root == NULL) {
return;
}
midOrder(root->left);
cout << root->data << " ";
midOrder(root->right);
}
//由前序遍历和中序遍历构建二叉树
Node* buildTree(char* pre, char* in, int n) {
if (n == 0) {
return NULL;
}
Node* root = new Node();
root->data = *pre;
char* p;
//在中序中找到根节点
for (p = in; p < in + n; p++) {
if (*p == *pre) {
break;
}
}
int left = p - in;//左子树个数
int right = n - left - 1;//右子树个数
//递归构建左子树
root->left = buildTree(pre + 1, in, left);
//递归构建右子树
root->right = buildTree(pre + left + 1, p + 1, right);
return root;
}
//二叉树
class BinTree {
protected:
int _size;
Node* _root;
public:
BinTree(char* pre, char* in, int n) { _root=buildTree(pre, in, n); }
Node* get_root() { return _root; }
};
int main() {
char pre[] = "idcabhfeglkjnmpo";
char in[] = "abcdefghijklmnop";
cout << "已知前序遍历:";
for (auto i : pre) cout << i << " "; cout << endl;
cout << "已知后序遍历:";
for (auto i : in) cout << i << " "; cout << endl;
int length = sizeof(pre) - 1;
BinTree tree=BinTree(pre, in, length);
Node* root = tree.get_root();
cout << "======对生成的二叉树进行遍历======" << endl;
//使用先序遍历和中序遍历验证构建的二叉树是否正确
cout << "先序遍历:"; preOrder(root); cout<<endl;
cout << "中序遍历:"; midOrder(root); cout << endl;
}