力扣中不要用static
/** * 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: int i = 0; void build(vector<int>& preorder, vector<int>& inorder, TreeNode* &root, int x, int y) { if(x > y) { root = NULL; return; } root = (TreeNode*) malloc(sizeof(TreeNode)); root->val = preorder[i++]; int j; for(j = x; j <= y && inorder[j] != root->val; j++); build(preorder, inorder, root->left, x, j - 1); build(preorder, inorder, root->right, j + 1, y); } TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) { TreeNode* root; build(preorder, inorder, root, 0, inorder.size() - 1); return root; } };