Lintcode72 Construct Binary Tree from Inorder and Postorder Traversal solution 题解
来源:互联网 发布:男人喜欢女人 知乎 编辑:程序博客网 时间:2024/06/16 11:21
题目描述】
Given inorder and postorder traversal of a tree, construct the binary tree.
Notice:You may assume that duplicates do not exist in the tree.
根据中序遍历和后序遍历树构造二叉树
注意:你可以假设树中不存在相同数值的节点
【题目链接】
www.lintcode.com/en/problem/construct-binary-tree-from-inorder-and-postorder-traversal/
【题目解析】
本题在属于二叉树遍历的经典题目,已知二叉树的两个遍历序列构造二叉树,有如下性质:
若已知先序和中序,则可以构造出唯一的二叉树
若已知先序和后序,则可以构造出多颗不同的二叉树
若已知中序和后序,则可以构造出唯一的二叉树
本题中我们已知的条件为中序遍历和后序遍历,所以我们一定可以构造出唯一的二叉树。
我们先将整棵树看作根节点和两颗子树,则其两种遍历得到的序列为
序列
可以肯定后序遍历序列中最后一个数一定是当前二叉树的根节点root。又因为二叉树不存在相同的数,我们可以找到root在中序遍历中位置p。
则我们可以分别找到两颗子树对应的中序和后序遍历:
左子树的中序= inOrder[1 .. p - 1]
左子树的后序= postOrder[1 .. p - 1]
右子树的中序= inOrder[p + 1 .. n]
右子树的后序= postOrder[p .. n - 1]
在此基础上我们就可以递归处理两颗子树。
当我们发现当前中序遍历和后序遍历长度都为1的时候,也就找到了叶子节点,此时我们开始回溯。
【参考答案】
www.jiuzhang.com/solutions/construct-binary-tree-from-inorder-and-postorder-traversal/
- Lintcode72 Construct Binary Tree from Inorder and Postorder Traversal solution 题解
- Lintcode72 Construct Binary Tree from Inorder and Postorder Traversal solution 题解
- LeetCode题解: Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode题解:Construct Binary Tree from Inorder and Postorder Traversal
- *(leetcode) Construct Binary Tree from Inorder and Postorder Traversal (tree)
- LeetCode[Tree]: Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode: Construct Binary Tree from Inorder and Postorder Traversal
- [LeetCode]Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode: Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode: Construct Binary Tree from Inorder and Postorder Traversal
- Construct Binary Tree from Inorder and Postorder Traversal
- [LeetCode] Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode Construct Binary Tree from Inorder and Postorder Traversal
- [Leetcode] Construct Binary Tree from Inorder and Postorder Traversal
- leetcode 110: Construct Binary Tree from Inorder and Postorder Traversal
- 【leetcode】Construct Binary Tree from Inorder and Postorder Traversal
- Construct Binary Tree from Inorder and Postorder Traversal
- unity3dC#的List升序降序排序
- linux下安装redis总结
- 基于 maven 的 ssm 项目搭建一:环境配置
- Hibernate使用注解方式完成双向多对多映射
- 大牛的未必必看,增长见识和知识啊
- Lintcode72 Construct Binary Tree from Inorder and Postorder Traversal solution 题解
- Java heap dump触发和分析
- linux下安装jdk1.8
- JNI开发
- 调用存储过程,函数,selectKey,sql,if,choose标签
- colorAccent,colorPrimary,colorPrimaryDark等
- 禅道——环境搭建
- bootp dhclient NetworkManager dbus dnsmasq resolvconf avahi关系厘清(持续更新)
- 线程的join 和detach状态(线程的分离与结合)