Description:
Given inorder and postorder traversal of a tree, construct the binary tree.
Note: You may assume that duplicates do not exist in the tree.
分析:
代码:
#include <iostream>
#include <vector>
#include <stack>
#define Elementype char
using namespace std;
using iter_int = vector<Elementype>::iterator;
typedef struct TreeNode //树结点
{
Elementype val;
TreeNode *left;
TreeNode *right;
TreeNode(Elementype x) : val(x), left(nullptr), right(nullptr) {}
} *Tree;
Tree BuildTree(iter_int in_b,iter_int in_e,iter_int post_b, iter_int post_e)
{
//终止条件
if (in_b == in_e)
return nullptr;
if (post_b == post_e)
return nullptr;
auto root = new TreeNode(*(post_e - 1));
auto location = find(in_b, in_e, *(post_e - 1));
auto leftsize = distance(in_b, location);
root->left = BuildTree(in_b, in_b + leftsize + 1, post_b, post_b + leftsize);
root->right = BuildTree(in_b + leftsize + 1, in_e, post_b + leftsize, post_e-1);
return root;
}
Tree ConstructBinaryTree(vector<Elementype>&in, vector<Elementype>&post) //构建二叉树
{
return BuildTree(in.begin(), in.end() , post.begin(), post.end() );
}
void PreorderTraversal(Tree root) //前序遍历
{
stack<Tree> sk;
sk.push(root);
while (!sk.empty())
{
auto p = sk.top();
cout << p->val << " ";
sk.pop();
if (p->right)
sk.push(p->right);
if (p->left)
sk.push(p->left);
}
}
void InorderTraversal(Tree root) //中序遍历
{
stack<Tree> sk;
Tree p = root;
while (p)
{
sk.push(p);
p = p->left;
}
while (!sk.empty())
{
p = sk.top();
cout << p->val << " ";
sk.pop();
if (p->right)
InorderTraversal(p->right);
}
}
void PostorderTraversal(Tree root) //后序遍历
{
stack<Tree> sk;
Tree p = root;
while (p)
{
sk.push(p);
p = p->left;
}
while (!sk.empty())
{
p = sk.top();
if (p->right)
PostorderTraversal(p->right);
cout << p->val << " ";
sk.pop();
}
}
int main()
{
vector<Elementype> Inorder = {'A','B','C','D','E','F','G'};
vector<Elementype> Postorder = { 'B','D','C','A','F','G','E'};
Tree root = ConstructBinaryTree(Inorder, Postorder);
cout << "前序遍历结果: ";
PreorderTraversal(root);
cout << endl;
cout << "中序遍历结果: ";
InorderTraversal(root);
cout << endl;
cout << "后序遍历结果: ";
PostorderTraversal(root);
cout << endl;
system("pause");
return 0;
}
测试: