LC 889. Construct Binary Tree from Preorder and Postorder Traversal

本文介绍了一种使用预序和后序遍历构建二叉树的方法,通过一个具体的例子展示了算法的实现过程。文章包含了一个C++代码示例,该示例通过递归方法构建二叉树,并讨论了使用map优化查找效率的尝试。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Return any binary tree that matches the given preorder and postorder traversals.

Values in the traversals pre and post are distinct positive integers.

 

Example 1:

Input: pre = [1,2,4,5,3,6,7], post = [4,5,2,6,7,3,1]
Output: [1,2,3,4,5,6,7]

 

Note:

  • 1 <= pre.length == post.length <= 30
  • pre[] and post[] are both permutations of 1, 2, ..., pre.length.
  • It is guaranteed an answer exists. If there exists multiple answers, you can return any of them.

Runtime: 20 ms, faster than 10.38% of C++ online submissions for Construct Binary Tree from Preorder and Postorder Traversal.

想用map优化查找left root的速度,结果更慢了....

#include <assert.h>
class Solution {
private:
  unordered_map<int,int>mp;
public:
  TreeNode* constructFromPrePost(vector<int>& pre, vector<int>& post) {
    for(int i=0; i<post.size(); i++) mp[post[i]] = i;
    return helper(pre, post, 0, pre.size()-1, 0, post.size()-1);
  }
  TreeNode* helper(vector<int>& pre, vector<int>& post, int pres, int pree, int poss, int pose){
    if(pres > pree || poss > pose) return nullptr;
    assert(pre[pres] == post[pose]);
    int rootval = pre[pres];
    TreeNode* root = new TreeNode(rootval);
    if(pres == pree && poss == pose) return root;
    int leftidx = mp[pre[pres+1]];
    int leftlength = leftidx - poss + 1;
    int leftpose = pres + leftlength;
    root->left = helper(pre, post, pres+1, leftpose, poss, leftidx);
    root->right = helper(pre, post, leftpose+1, pree, leftidx+1, pose-1);
    return root;
  }
};

 

转载于:https://www.cnblogs.com/ethanhong/p/10191384.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值