/**
* 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 {
int rs=0;
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder, int sis, int eis) {
if(rs>preorder.size()-1) return nullptr;
TreeNode* root= new TreeNode(preorder[rs]);
TreeNode* cur=root;
int nis;
for(int i=sis;i<eis;i++)
if(inorder[i]==preorder[rs]) {nis=i; break;}
if(nis>sis) {rs++; root->left = buildTree(preorder,inorder,sis,nis-1);}
if(nis<eis) { rs++;root->right = buildTree(preorder, inorder, nis+1,eis);}
return root;
}
public:
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
if(preorder.empty() || inorder.empty()) return nullptr;
return buildTree(preorder, inorder, 0,inorder.size()-1);
}
};
执行用时 :44 ms, 在所有 C++ 提交中击败了41.72%的用户
内存消耗 :17.4 MB, 在所有 C++ 提交中击败了45.45%的用户