1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
|
class Solution { public: TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) { if(preorder.empty()) return nullptr; return buildBinaryTree(preorder, 0, preorder.size(), inorder, 0, inorder.size()); } TreeNode* buildBinaryTree(vector<int> &preorder, int preLeft, int preRight, vector<int> &inorder, int inLeft, int inRight){ if(preLeft >= preRight || inLeft >= inRight) return nullptr; TreeNode *node = new TreeNode(preorder[preLeft]); int rootPosInOrder; for(int i = inLeft; i < inRight; i++){ if(inorder[i] == node->val){ rootPosInOrder = i; break; } } int leftNum = rootPosInOrder - inLeft, rightNum = inRight - rootPosInOrder - 1; node->left = buildBinaryTree(preorder, preLeft + 1, preLeft + 1 + leftNum, inorder, inLeft, inLeft + leftNum); node->right = buildBinaryTree(preorder, preLeft + 1 + leftNum, preRight, inorder, inLeft + leftNum + 1, inRight); return node; } };
|