1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| TreeNode * makeTree(vector<int>& preorder, vector<int>& inorder, int index, int left, int right) { if (left > right)return nullptr; TreeNode* root = new TreeNode(preorder[index]); if (left == right)return root; int i = left; while (inorder[i] != preorder[index])i++; root->left = makeTree(preorder, inorder, index + 1, left, i - 1); root->right = makeTree(preorder, inorder, index + i - left + 1, i + 1, right); return root; }
TreeNode * buildTree(vector<int>& preorder, vector<int>& inorder) { int right = inorder.size(); if (!right)return nullptr; return makeTree(preorder, inorder, 0, 0, right-1); }
|