LeetCode 889-Construct Binary Tree from Preorder and Postorder Traversal(二叉树,前序+后序序列构造二叉树)

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;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值