作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/


题目地址:https://leetcode.com/problems/construct-binary-tree-from-preorder-and-postorder-traversal/description/

题目描述

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.

题目大意

根据先序遍历和后序遍历,重建二叉树。

解题方法

讲道理的话,只知道前序和后序遍历是没法确定一棵二叉树的。所以,这个题指明了不含重复元素,而且如果有多棵二叉树返回其中的一种即可。

其实做法还是很简单的。前序和后序的遍历并没有打乱整棵树的关系,一棵树的节点在两种遍历方式所得到的还都是在一块的。

所以pre[0]是根节点,也就是post[-1];

post[-2]时候右子树的根节点,因此在前序遍历中找到post[-2]的位置idx就能分开两棵子树。

# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None class Solution(object):
def constructFromPrePost(self, pre, post):
"""
:type pre: List[int]
:type post: List[int]
:rtype: TreeNode
"""
if not pre or not post: return None
root = TreeNode(pre[0])
if len(pre) == 1:
return root
idx = pre.index(post[-2])
root.left = self.constructFromPrePost(pre[1:idx], post[:idx-1])
root.right = self.constructFromPrePost(pre[idx:], post[idx-1:-1])
return root

下面C++代码为了防止平凡的构建子数组,所以使用索引的方式切割数组。C++中,如果函数使用传值的方式进行参数传递,就会调用对象的拷贝构造函数,使得代码效率变慢。所以,一般使用传引用的方式加快函数传参的次数。下面的代码中,pre 和 post使用引用传递,[a,b]表示目前处理的pre区间,[c,d]表示目前处理的post区间。

代码如下:

/**
* 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:
TreeNode* constructFromPrePost(vector<int>& pre, vector<int>& post) {
const int N = pre.size();
for (int i = 0; i < N; i++) m_[post[i]] = i;
return construct(pre, post, 0, N - 1, 0, N - 1);
}
private:
unordered_map<int, int> m_;
// pre[a, b], post[c, d]
TreeNode* construct(vector<int>& pre, vector<int>& post, int a, int b, int c, int d) {
TreeNode* root = new TreeNode(pre[a]);
if (a == b) return root;
int t = pre[a + 1];
int idx = m_[t];
int len = idx - c + 1;
root->left = construct(pre, post, a + 1, a + len, c, c + len - 1);
if (idx + 1 == d) return root;
root->right = construct(pre, post, a + len + 1, b, idx + 1, d - 1);
return root;
}
};

参考资料:

https://leetcode.com/problems/construct-binary-tree-from-preorder-and-postorder-traversal/discuss/161651/Easy-Python-Recursive-Solution-with-Explanation

日期

2018 年 9 月 4 日 ———— 迎接明媚的阳光!
2018 年 12 月 8 日 —— 今天球打的不错,很舒服

【LeetCode】889. Construct Binary Tree from Preorder and Postorder Traversal 解题报告(Python & C++)的更多相关文章

  1. [LeetCode] 889. Construct Binary Tree from Preorder and Postorder Traversal 由先序和后序遍历建立二叉树

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

  2. LeetCode 889. Construct Binary Tree from Preorder and Postorder Traversal

    原题链接在这里:https://leetcode.com/problems/construct-binary-tree-from-preorder-and-postorder-traversal/ 题 ...

  3. (二叉树 递归) leetcode 889. Construct Binary Tree from Preorder and Postorder Traversal

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

  4. 【LeetCode】106. Construct Binary Tree from Inorder and Postorder Traversal 解题报告

    [LeetCode]106. Construct Binary Tree from Inorder and Postorder Traversal 解题报告(Python) 标签: LeetCode ...

  5. LC 889. Construct Binary Tree from Preorder and Postorder Traversal

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

  6. LeetCode: Construct Binary Tree from Preorder and Inorder Traversal 解题报告

    Construct Binary Tree from Preorder and Inorder Traversal Given preorder and inorder traversal of a ...

  7. LeetCode: Construct Binary Tree from Inorder and Postorder Traversal 解题报告

    Construct Binary Tree from Inorder and Postorder Traversal Given inorder and postorder traversal of ...

  8. 【原创】leetCodeOj ---Construct Binary Tree from Preorder and Inorder Traversal 解题报告

    原题地址: https://oj.leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/ 题目 ...

  9. C++版-剑指offer 面试题6:重建二叉树(Leetcode105. Construct Binary Tree from Preorder and Inorder Traversal) 解题报告

    剑指offer 重建二叉树 提交网址: http://www.nowcoder.com/practice/8a19cbe657394eeaac2f6ea9b0f6fcf6?tpId=13&tq ...

随机推荐

  1. Linux-root管理员创建新用户

    Linux 系统是一个多用户多任务的分时操作系统,任何一个要使用系统资源的用户,都必须首先向系统管理员申请一个账号,然后以这个账号的身份进入系统.用户的账号一方面可以帮助系统管理员对使用系统的用户进行 ...

  2. 微信第三方平台获取component_verify_ticket

    官方文档说明: 在公众号第三方平台创建审核通过后,微信服务器会向其"授权事件接收URL"每隔10分钟定时推送component_verify_ticket.第三方平台方在收到tic ...

  3. 2.MaxSubArray-Leetcode

    题目:最大连续子序列和 思路:动态规划 状态转移方程 f[j]=max{f[j-1]+s[j],s[j]}, 其中1<=j<=n target = max{f[j]}, 其中1<=j ...

  4. 谈一谈 DDD

    一.前言 最近 10 年的互联网发展,从电子商务到移动互联,再到"互联网+"与传统行业的互联网转型,是一个非常痛苦的转型过程.在这个过程中,一方面会给我们带来诸多的挑战,另一方面又 ...

  5. 连接查询条件在on后面和条件在where后面

    emp表结构如下: dept表结构如下: 内连接 条件语句放在on 后面和 where 结果对于inner join结果是一样的 但对于left join 结果会产生不一样 这种现象也比较好理解,如果 ...

  6. shell awk命令字符串拼接

    本节内容:awk命令实现字符串的拼接 输入文件的内容: TMALL_INVENTORY_30_GROUP my163149.cm6 3506 5683506 mysql-bin.000013 3273 ...

  7. Turbine使用

    一.简介 Turbine是聚合服务器发送事件流数据的一个工具,Hystrix的监控中,只能监控单个节点,实际生产中都为集群,因此可以通过Turbine来监控集群下Hystrix的metrics情况 T ...

  8. 7、Redis五大数据类型---集合(Set)

    一.集合(Set)简介 Set是string类型的无序集合.集合成员是唯一的,这就意味着集合中不能出现重复的数据. Redis 中 集合是通过哈希表实现的,所以添加,删除,查找的复杂度都是O(1). ...

  9. 魅族CMDB运维自动化实践

    一.简介 原创:梁鹏 本文是根据魅族系统架构师梁鹏10月20日在msup携手魅族.Flyme.百度云主办的第十三期魅族技术开放日< 魅族CMDB运维自动化实践>演讲中的分享内容整理而成. ...

  10. gitlab 备份&恢复

    Gitlab 成功运行起来之后,最终的事情就是定期的备份,遇到问题后的还原. 备份配置 默认 Gitlab 的备份文件会创建在/var/opt/gitlab/backups文件夹中,格式为时间戳_日期 ...