題目:
給定兩個整數陣列,分別表示二元樹的前序遍歷和中序遍歷結果,請構造該二元樹並回傳其根節點。
範例:
前序遍歷 (preorder) = [3, 9, 20, 15, 7]
中序遍歷 (inorder) = [9, 3, 15, 20, 7]
回傳的二元樹為:
3
/ \
9 20
/ \
15 7
實作:
class Solution {
public:
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
unordered_map<int, int> inorder_map;
for (int i = 0; i < inorder.size(); i++) {
inorder_map[inorder[i]] = i;
}
return buildTree(preorder, 0, preorder.size() - 1, inorder, 0, inorder.size() - 1, inorder_map);
}
private:
TreeNode* buildTree(vector<int>& preorder, int preStart, int preEnd,
vector<int>& inorder, int inStart, int inEnd,
unordered_map<int, int>& inorder_map) {
if (preStart > preEnd || inStart > inEnd) return nullptr;
int rootVal = preorder[preStart];
TreeNode* root = new TreeNode(rootVal);
int inRootIndex = inorder_map[rootVal];
int numsLeft = inRootIndex - inStart;
root->left = buildTree(preorder, preStart + 1, preStart + numsLeft, inorder, inStart, inRootIndex - 1, inorder_map);
root->right = buildTree(preorder, preStart + numsLeft + 1, preEnd, inorder, inRootIndex + 1, inEnd, inorder_map);
return root;
}
};