Lintcode72 Construct Binary Tree from Inorder and Postorder Traversal solution 题解
来源:互联网 发布:未来房价发展趋势知乎 编辑:程序博客网 时间:2024/06/05 08:42
【题目描述】
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
- leetCode之Longest Substring Without Repeating Characters实现
- 十年程序人生__转自黎活明
- git 远程仓库和本地仓库建立连接
- 栈和队列的python实现
- React-Native之Android(6.0及以上)权限申请
- Lintcode72 Construct Binary Tree from Inorder and Postorder Traversal solution 题解
- 自定义视图之 重写函数 ondraw()
- Android 图像视图ImageView
- 寄存器参考
- 【C++】浅析C++中的继承
- Java将秒换算成天、时、分、秒格式
- BZOJ 2654 tree(二分答案+最小生成树)
- C语言学习历程(一)数据类型及变量之心得体会
- Hibernate(八)多表联查之双向一对一