要求:前序中序建树
思路:必然要有四个下标,递归。可以加一个哈希表存中序根hash[in[i]]=i。迭代法太复杂且不通用
/**
* 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* build(vector<int>& preorder, vector<int>& inorder,int pl,int pr,int il,int ir){
if(il>ir)return nullptr;
TreeNode* root=new TreeNode(preorder[pl]);
int inrootindex=il;
while(inorder[inrootindex]!=preorder[pl])++inrootindex;
root->left=build(preorder,inorder,pl+1,pl+inrootindex-il,il,inrootindex-1);
root->right=build(preorder,inorder,pl+inrootindex-il+1,pr,inrootindex+1,ir);
return root;
}
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
return build(preorder,inorder,0,preorder.size()-1,0,inorder.size()-1);
}
};