根据一棵树的中序遍历与后序遍历构造二叉树。
注意:
你可以假设树中没有重复的元素。
例如,给出
中序遍历 inorder = [9,3,15,20,7]
后序遍历 postorder = [9,15,7,20,3]
返回如下的二叉树:
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路:本题思路和重建二叉树一样。
- 首先根据存储每个元素在中序遍历中的索引;
- 构造一个函数,根据在后序序列中确定的根节点确定在中序序列中左右子树的范围。
- 根据此写出函数
// 传入参数:后序,中序,后序序列根节点,中序序列左边界,中序序列右边界construct(vector<int>& postorder,vector<int>& inorder,int post_root,int in_left,int in_right)
- 那么,右子树在后序遍历中的根节点在
post_root - 1
,右子树在中序遍历中的边界为[in_root+1,in_right]
;左子树在后序遍历中的根节点在post_root - 右子树长度 - 1
,左子树在中序遍历中的边界为[in_left,in_root-1]
/**
* 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 {
public:
unordered_map<int,int> Map;//存储中序遍历的下标索引
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
if(postorder.size() == 0||inorder.size() == 0)
{
return nullptr;
}
for(int i = 0;i<inorder.size();++i)
{
Map[inorder[i]] = i;
}
// 传入参数:后序,中序,后序序列根节点,中序序列左边界,中序序列右边界
return construct(postorder,inorder,postorder.size()-1,0,inorder.size()-1);
}
TreeNode* construct(vector<int>& postorder,vector<int>& inorder,int post_root,int in_left,int in_right)
{
//停止条件
if(in_left > in_right)
return nullptr;
TreeNode* root = new TreeNode(postorder[post_root]);
//根节点在中序遍历中的位置 用于划分左右子树的边界
int in_root = Map[postorder[post_root]];
//右子树在后序遍历中的根节点在post_root - 1
//右子树在中序遍历中的边界为[in_root+1,in_right]
root->right = construct(postorder,inorder,post_root - 1,in_root + 1,in_right);
//左子树在后序遍历中的根节点在post_root - 右子树长度 - 1
//左子树在中序遍历中的边界为[in_left,in_root-1]
root->left = construct(postorder,inorder,post_root - (in_right - in_root + 1),in_left,in_root -1);
return root;
}
};