LeetCode 889-Construct Binary Tree from Preorder and Postorder Traversal
题干:
给定一棵二叉树的前序遍历序列和后序遍历序列,要求构造出这棵二叉树来。如果存在多种构造方式,构造其中任意一种都可以。注:二叉树节点的值不存在重复(即序列内没有重复元素)。
解:
前序遍历:中左右;后序遍历:左右中
所以根节点对应前序序列第一个值,也对于后序序列最后一个值。
一种构造二叉树的方法是:
- 把前序序列第一个值(也即后序序列最后一个值)确定为根节点的值;
- 把前序序列第二个值作为左子树的根节点的值;
- 在后序序列中寻找左子树根节点的值,能够确定左右子树的范围,递归构造即可。
但这种方法构造的二叉树可能不唯一。不唯一的原因在于,把preL+1
认为是左子树的根节点,实际上左子树有可能为空。
unordered_map<int,int> mp;
TreeNode* constructFromPrePost(vector<int>& preorder, vector<int>& postorder) {
int n = preorder.size();
if(!n) return nullptr;
for(int i = 0; i < n; i++) mp[postorder[i]] = i;
return build(preorder, 0, n-1, postorder, 0, n-1);
}
TreeNode* build(vector<int>& preorder, int preL, int preR, vector<int> postorder, int postL, int postR){
if(preL > preR) return nullptr;
if(preR == preL)
return (new TreeNode(preorder[preL]));
int rootval = preorder[preL];
TreeNode *root = new TreeNode(rootval);
int leftval = preorder[preL+1];
int indexLeft = mp[leftval];
int cntLeft = indexLeft + 1 - postL;
root->left = build(preorder, preL + 1, preL + 1 + cntLeft - 1, postorder, postL, indexLeft);
root->right = build(preorder, preL + 1 + cntLeft, preR, postorder, indexLeft + 1, postR - 1);
return root;
}