剑指offer-4:重建二叉树
给定:
前序遍历是:[3, 9, 20, 15, 7]
中序遍历是:[9, 3, 15, 20, 7]
返回:[3, 9, 20, null, null, 15, 7, null, null, null, null]
返回的二叉树序列如下所示:
3
/ \
9 20
/ \
15 7
前序遍历(根左右)3-9-20-15-7
中序遍历(左根右)9-3-15-20-7
处理思想:递归,时间复杂度O(n)
1.利用前序遍历寻找根节点,遍历的第一个数即为根节点的值;
2.在中序遍历中找到根节点的位置k,则k左边是左子树的中序遍历,右边是右子树的中序遍历;
3.如果左子树的中序遍历长度为l,则在前序遍历中,根节点之后的l个数即为左子树的前序遍历,剩下的即为右子树的前序遍历;
4.得到左右子树的前中序遍历后,即可以递归创建左右子树,再创建根节点;
由于用哈希表记录每个值在中序遍历中的位置,因此在中序遍历中查找根节点的位置只需要O(1)的时间,创建每个节点需要的时间为O(1),总体时间复杂度为O(n)。
代码如下:
class Solution {
public:
unordered_map<int, int> pos;
TreeNode* reConstructBinaryTree(vector<int>& preorder,vector<int>& inorder) {
int n = preorder.size();
for(int i = 0; i < n; i++){
pos[inorder[i]] = i; //opps
}
return dfs(preorder, inorder, 0, n - 1, 0, n - 1);
}
TreeNode* dfs(vector<int>& pre, vector<int>& in, int pl, int pr, int il, int ir){
if(pl > pr) return nullptr;
int k = pos[pre[pl]] - il;
TreeNode* root = new TreeNode(pre[pl]);
root->left = dfs(pre, in, pl + 1 , pl + k, il, il + k - 1); //opps
root->right = dfs(pre, in, pl + k + 1, pr, il + k + 1, ir); //opps
return root;
}
};