class Solution {
public:
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
return reBuild(inorder, postorder);
}
TreeNode* reBuild(vector<int> mid, vector<int> pos) {
if (pos.empty())
return nullptr;
TreeNode* newNode = new TreeNode(*pos.rbegin());
int i = 0 ;
//找到他在中序中的位置
for (; i < mid.size(); ++i)
if (mid[i] == *pos.rbegin())
break;
pos.pop_back();
vector<int>L_next_mid,L_next_pos, R_next_mid, R_next_pos;
//切割左字串
for (int k = 0; k < i; ++k)
L_next_mid.push_back(mid[k]);
for (int k = 0; k < L_next_mid.size();++k)
L_next_pos.push_back(pos[k]);
//切割右字串
for (int k = i + 1; k < mid.size(); ++k)
R_next_mid.push_back(mid[k]);
for (int k = L_next_pos.size(); k < pos.size(); ++k)
R_next_pos.push_back(pos[k]);
newNode->left = reBuild(L_next_mid,L_next_pos);
newNode->right = reBuild(R_next_mid, R_next_pos);
return newNode;
}
};
猪比思路,每次pos的最后一个元素都是当前树的根节点,然后再分别切割出子左树的中序和后序、右子树的中序和后序,进行递归,成功打败了自己
效率低的原因:
每次构造子树的时候都需要遍历一次inorder数组来找到树根的下标,所以不妨直接一开始就使用hashMap来映射数字及其下标,这样的话能极大提高运行效率!!
标签:back,int,reBuild,mid,next,力扣,pos,二叉树,106 From: https://www.cnblogs.com/Syukuu/p/16725768.html