1.后序遍历的最后一个一定是根节点
2.去中序找这个根节点,找到之后左右两边一下子就把左子树和右子树找到了
3.就可以又在后序遍历里切割
4.后序遍历里左右子树,如果比较长,那么最后一个值一定是该节点的根节点
5.会一直从左子树进去,每次的leftinorder rightorder leftposorder rightposorder都会改变,返回上一层之后又改变了
class Solution {
private:
TreeNode *travelsal(vector<int>& inorder, vector<int>& postorder){
if(postorder.size()==0)return NULL;
int posvalue=postorder[postorder.size()-1];
TreeNode *root=new TreeNode(posvalue);
if(postorder.size()==1)return root;
int i;
for( i=0;i<inorder.size();i++){
if(inorder[i]==posvalue)break;
}
vector<int>leftinorder(inorder.begin(),inorder.begin()+i);
vector<int>rightinorder(inorder.begin()+i+1,inorder.end());
postorder.resize(postorder.size()-1);
vector<int>leftposorder(postorder.begin(),postorder.begin()+leftinorder.size());
vector<int>rightposorder(postorder.begin()+leftinorder.size(),postorder.end());
root->left=travelsal(leftinorder,leftposorder);
root->right=travelsal(rightinorder,rightposorder);
return root;
}
public:
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
if(!inorder.size()||!postorder.size())return NULL;
return travelsal(inorder,postorder);
}
};