/*
解题思路
1.根据后序序列最后一个元素建立根节点;
2.在中序序列中找到该元素,确定根节点的左右子树序列;
3.在后序序列中确定左右子树的后序序列;
4.由左子树的中序和后序序列建立左子树;
5.由右子树的中序和后序序列建立右子树;
例子
7 //元素个数
2 3 1 5 7 6 4 //后序遍历序列
1 2 3 4 5 6 7 //中序遍历序列
取出后序序列最后一个元素4,将中序遍历分为 1 2 3 和 5 6 7两组
处理1 2 3,其后序序列为2 3 1
取出左子树的根1 将左子树分为 空 和右:2 3
……
实现代码如下
*/
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
typedef struct TreeNode
{
int data;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : data(x), left(NULL), right(NULL) {}
} * treeNode;
class Solution
{
public:
TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder)
{
TreeNode *root = NULL;
if (postorder.size() == 0)
return NULL;
int post_last = postorder.size() - 1;
int loc = 0;
while (postorder[post_last] != inorder[loc] && loc < inorder.size())
loc++;
root = new TreeNode(postorder[post_last]);
//处理左子树
vector<int> l_post(postorder.begin(), postorder.begin() + loc);
vector<int> l_in(inorder.begin(), inorder.begin() + loc);
root->left = buildTree(l_in, l_post);
l_post.clear();
l_in.clear();
//处理右子树
vector<int> r_post(postorder.begin() + loc, postorder.end() - 1);
vector<int> r_in(inorder.begin() + loc + 1, inorder.end());
root->right = buildTree(r_in, r_post);
r_post.clear();
r_in.clear();
return root;
}
//按层遍历输出
//思路:先将根入队列,判断其左右子树是否为空,不空,入队,继续该操作,从对头访问序列
void levelOrder(TreeNode *root)
{
queue<TreeNode *> que;
TreeNode *T = root;
que.push(T);
while (!que.empty())
{
T = que.front();
cout << T->data << " ";
que.pop();
if (T->left)
que.push(T->left);
if (T->right)
que.push(T->right);
}
cout << endl;
}
};
int main()
{
int n;
cin >> n;
vector<int> inorder(n);
vector<int> postorder(n);
for (int i = 0; i < n; i++)
cin >> postorder[i];
for (int i = 0; i < n; i++)
cin >> inorder[i];
Solution solution;
TreeNode *root = solution.buildTree(inorder, postorder);
solution.levelOrder(root);
return 0;
}
C++ 由后序和中序遍历确定二叉树
最新推荐文章于 2025-07-18 17:31:50 发布