105. Construct a binary tree from pre-order and middle-order traversal sequence
Medium difficulty 930
The binary tree is constructed according to the pre-order traversal and the middle-order traversal of a tree.
Note:
You can assume that there are no duplicate elements in the tree.For example, given
Preorder traversal preorder = [3,9,20,15,7] Inorder traversal inorder = [9,3,15,20,7]Return the following binary tree:
3 / \ 9 20 / \ 15 7
Idea analysis:
The main idea is this, the middle order traversal can get the root node of a tree, and then through the preorder traversal and the root node, you can know the number of nodes in the left and right subtrees of the tree, and then continue to perform recursive operations. A left subtree and a right subtree can be constructed, and finally connected to the root node to form a binary tree.
It should be noted that the mapping position, that is, the location of the root node, can be regarded as the location of the root node of each subtree. The official solution to the problem is to put the sequence of the middle-order traversal into the hash table, which can quickly help find the root node.
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
unordered_map<int, int> index;
TreeNode* myBuildTree(const vector<int>& preorder, const vector<int>& inorder, int pre_left, int pre_right, int in_left, int in_right){
if (pre_left > pre_right){
return nullptr;
}
int pre_root = pre_left;//前序遍历中根节点位置
int in_root = index[preorder[pre_root]];//中序遍历中根节点位置
TreeNode* root = new TreeNode(preorder[pre_root]);
int size_left_subTree = in_root - in_left; //两位置只差为左子树节点个数
root->left = myBuildTree(preorder, inorder, pre_left+1, pre_left+ size_left_subTree, in_left, in_root-1);
root->right = myBuildTree(preorder, inorder, pre_left+size_left_subTree+1, pre_right, in_root+1, in_right);
return root;
}
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
int n = preorder.size();
for(int i = 0; i < n; i++){
index[inorder[i]] = i;
}
return myBuildTree(preorder, inorder, 0, n-1, 0, n-1);
}
};
Afterword:
It's been a long time, now I'm starting to practice algorithm again, come on!