Article Directory
Method 1: Recursion: time O(n), space O(n)
answer:
- According to the index in the pre-order, find the corresponding position k in the middle-order
- Create a node, divide the left tree of the node before the k position, and the right tree of the node after the k position
- End condition: index to the beginning or left == right
- Here a map key-value pair is used to store the value and index of the middle order, and the search time complexity of the map is O(1)
class Solution {
public:
int index = 0; // 先序的索引
unordered_map<int, int> board; // 用来保存中序的值和索引
TreeNode* build(vector<int>& preorder, int left, int right)
{
if (index == preorder.size() || left == right)
return NULL;
int pos = board[preorder[index]];
TreeNode* root = new TreeNode(preorder[index]);
index++;
root->left = build(preorder, left, pos);
root->right = build(preorder, pos + 1, right);
return root;
}
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder)
{
if (preorder.size() == 0)
return NULL;
// 保存中序的键值对
for (int i = 0; i < inorder.size(); i++)
{
board[inorder[i]] = i;
}
return build(preorder, 0, preorder.size());
}
};