菜鸡思路:
经典问题,根据前序遍历和中序遍历结果构造二叉树,其实就是根据前序遍历结果去把中序遍历结果分成左右两个部分。再去分别递归构造。
菜鸡代码:
/**
* 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 {
private:
unordered_map<int, int> myMap;
public:
TreeNode* myBuildTree(const vector<int>& preorder, const vector<int>& inorder, int preorderLeft, int preorderRight, int inorderLeft, int inorderRight) {
if (preorderLeft > preorderRight) {
return NULL;
}
int preorderRoot = preorderLeft;
int inorderRoot = myMap[preorder[preorderRoot]];
TreeNode* root = new TreeNode(preorder[preorderRoot]);
int leftSubtreeSize = inorderRoot - inorderLeft;
root->left = myBuildTree(preorder, inorder, preorderLeft + 1, preorderLeft + leftSubtreeSize, inorderLeft, inorderRoot - 1);
root->right = myBuildTree(preorder, inorder, preorderLeft + leftSubtreeSize + 1, preorderRight, inorderRoot + 1, inorderRight);
return root;
}
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
int n = (int)preorder.size();
for (int i = 0; i < n; ++i) {
myMap[inorder[i]] = i;
}
return myBuildTree(preorder, inorder, 0, n - 1, 0, n - 1);
}
};