```cpp
class Solution {
public:
TreeNode* traversal(vector<int>& inorder, vector<int>& postorder) {
//后序为空返回空
if (postorder.size() == 0) return NULL; //可以去掉这句话
//取后序的末尾结点进行切割
int rootValue = postorder[postorder.size() - 1];
//以后序末尾结点创建一个根节点,开始构造树
TreeNode* root = new TreeNode(rootValue);
//说明这是叶子结点,则不需要再切割了,直接返回即可
if (postorder.size() == 1) {
return root;
}
//先开始切割中序,因为更加容易
//找到切割点
int depoint;
for (depoint = 0; depoint < inorder.size(); depoint++) {
if (inorder[depoint] == rootValue) break;
}
//开始切割,同时除去切割垫
//区间[0 , depoint) 共depoint个元素
vector<int> leftInorder(inorder.begin(), inorder.begin() + depoint);
vector<int> rightInorder(inorder.begin() + depoint + 1, inorder.end());
//切割后序,切割先序后,则知道了后序要切多少。记得要省去最后一个结点
vector<int> leftPostorder(postorder.begin(), postorder.begin() + leftInorder.size());
vector<int> rightPostorder(postorder.begin() + leftInorder.size(), postorder.end() - 1);
//迭代
root->left = traversal(leftInorder, leftPostorder);
root->right = traversal(rightInorder, rightPostorder);
return root;
}
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
if (inorder.size() == 0 || postorder.size() == 0) return NULL;
return traversal(inorder, postorder);
}
};
步骤
第一步:如果数组大小为零的话,说明是空节点了。
第二步:如果不为空,那么取后序数组最后一个元素作为节点元素。
第三步:找到后序数组最后一个元素在中序数组的位置,作为切割点
第四步:切割中序数组,切成中序左数组和中序右数组 (顺序别搞反了,一定是先切中序数组)
第五步:切割后序数组,切成后序左数组和后序右数组
第六步:递归处理左区间和右区间
思路注释已经写的很清楚了
以下是知道先序遍历构造二叉树
```cpp
class Solution {
public:
TreeNode* traversal(vector<int>& preorder, vector<int>& inorder) {
if (preorder.size() == 0) return NULL;
int rootValue = preorder[0];
TreeNode* root = new TreeNode(rootValue);
if (preorder.size() == 1) {
return root;
}
int depoint;
for (depoint = 0; depoint < inorder.size(); depoint++) {
if (inorder[depoint] == rootValue) break;
}
vector<int> leftInorder(inorder.begin(), inorder.begin() + depoint);
vector<int> rightInorder(inorder.begin() + depoint + 1, inorder.end());
vector<int> leftPreorder(preorder.begin() + 1, preorder.begin() + 1 + depoint);
vector<int> rightPreorder(preorder.begin() + 1 + depoint, preorder.end());
root->left = traversal(leftPreorder, leftInorder);
root->right = traversal(rightPreorder, rightInorder);
return root;
}
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
if (preorder.size() == 0 || inorder.size() == 0) return NULL;
return traversal(preorder, inorder);
}
};