此题与Leetcode105.Construct_Binary_Tree_From_Preorder_And_Inorder_Traversal的思路基本相同。
唯一的不同是后序遍历得到的数组顺序是左—右—根,从后向前(或反转后从前向后)先找到的根的右子树,而105题中先找到的是左子树。
时间复杂度:O(N^2)
C++代码:
class Solution {
public:
TreeNode * buildTree(vector<int>& inorder, vector<int>& postorder) {
if (inorder.empty())
return nullptr;
reverse(postorder.begin(), postorder.end());
return buildSubTree(postorder, 0, inorder, 0, inorder.size() - 1);
}
TreeNode* buildSubTree(vector<int>& postorder, int stP, vector<int>& inorder, int stI, int enI)
{
TreeNode* root = new TreeNode(postorder[stP]);
auto it = find(inorder.begin() + stI, inorder.begin() + enI, root->val);
int leftLen = (it - inorder.begin()) - stI, rightLen = (inorder.begin() + enI - it);
if (leftLen > 0)
root->left = buildSubTree(postorder, stP + rightLen + 1, inorder, stI, stI + leftLen - 1);
if (rightLen > 0)
root->right = buildSubTree(postorder, stP + 1, inorder, it - inorder.begin() + 1, enI);
return root;
}
};