题目
中序+后序->建树
思路
思路01
后序确定根(最后一个),中序中用根分割左中右
思路02
利用hashmap,优化中序中每次查找根索引的操作
Code
Code 01
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
return generate_tree(postorder, inorder, 0, postorder.size()-1, 0, inorder.size()-1);
}
private:
TreeNode * generate_tree(vector<int>& postorder, vector<int>& inorder, int pl, int pr, int il, int ir){
if(il>ir)return NULL;
int k=il;
while(k<ir&&inorder[k]!=postorder[pr])k++; //中序中找到当前根节点
TreeNode* root=new TreeNode(postorder[pr]);
root->left=generate_tree(postorder,inorder,pl,pl+(k-il)-1,il, k-1);
root->right=generate_tree(postorder,inorder,pl+(k-il),pr-1,k+1, ir);
return root;
}
};