C++/代码:
class Solution { public: map<int,int> hash; //用hash算法 vector<int> preorder,inorder; //定义全局变量 TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> vin) { preorder = pre, inorder = vin; //为全局变量赋值 for(int i = 0; i < inorder.size(); i ++) hash[inorder[i]] = i; //为中序序列排上号 return def(0,preorder.size()-1,0,inorder.size()); //确定二叉树区间范围 } TreeNode* def(int pl,int pr,int il,int ir){ if(pl > pr) return nullptr; auto root = new TreeNode(preorder[pl]); int k = hash[root->val];//寻找根节点的hash位置 auto left = def(pl + 1,pl - il + k,il,k - 1);//二叉树左分支的区间范围 auto right = def(pl - il + k + 1,pr,k + 1,ir);//二叉树右分支的区间范围 root->left = left,root->right = right; return root; } };