Lintcode73 Construct Binary Tree from Preorder and Inorder Traversal solution 题解
来源:互联网 发布:淘宝怎么回收手机 编辑:程序博客网 时间:2024/06/01 21:43
【题目描述】
Given preorder and inorder 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-preorder-and-inorder-traversal/
【题目解析】
相信学过数据结构的同学应该都对这道题目有深刻的印象,虽然它是二叉树的题目,但是其更多使用到的还是分治的思想。
对于给定的前序遍历preorder和中序遍历inorder,首先我们不难发现,这棵树的根结点其实就是preorder[0]。由于preorder和inorder是对同一棵树的遍历,我们可以知道preorder[0]在inorder中一定也存在,不妨设preorder[0]==inorder[k]。
由于inorder是中序遍历,所以k左边的就是根节点左子树的中序遍历、k右边的就是根节点右子树的中序遍历。
并且,由于我们已经知道了根节点左子树的节点数(与中序遍历长度相同),不妨设为l,我们可以知道preorder从1到l+1就是根节点左子树的前序遍历,剩下的最后一部分就是根节点右子树的前序遍历。
也就是说,我们可以计算出左子树、右子树的前序遍历和中序遍历,从而可以用分治的思想,将规模较大的问题分解成为两个较小的问题,然后递归的进行处理,还原左子树和右子树,最后连通根节点一起组成一棵完整的树。
【参考答案】
www.jiuzhang.com/solutions/construct-binary-tree-from-preorder-and-inorder-traversal/
- Lintcode73 Construct Binary Tree from Preorder and Inorder Traversal solution 题解
- Lintcode73 Construct Binary Tree from Preorder and Inorder Traversal solution 题解
- [LeetCode] Construct Binary Tree from Preorder and Inorder Traversal, Solution
- LeetCode题解: Construct Binary Tree from Preorder and Inorder Traversal
- LeetCode题解:Construct Binary Tree from Preorder and Inorder Traversal
- LeetCode题解:Construct Binary Tree from Preorder and Inorder Traversal
- *(leetcode) Construct Binary Tree from Preorder and Inorder Traversal (tree)
- LeetCode[Tree]: Construct Binary Tree from Preorder and Inorder Traversal
- [leetcode][tree] Construct Binary Tree from Preorder and Inorder Traversal
- Construct Binary Tree from Preorder and Inorder Traversal & Construct Binary Tree from Inorder and P
- LeetCode: Construct Binary Tree from Preorder and Inorder Traversal
- Construct Binary Tree from Preorder and Inorder Traversal
- [LeetCode]Construct Binary Tree from Preorder and Inorder Traversal
- LeetCode Construct Binary Tree from Preorder and Inorder Traversal
- [Leetcode] Construct Binary Tree from Preorder and Inorder Traversal
- Leetcode: Construct Binary Tree from Preorder and Inorder Traversal
- [LeetCode] Construct Binary Tree from Preorder and Inorder Traversal
- LeetCode Construct Binary Tree from Preorder and Inorder Traversal
- Ceres使用(三)
- 滤波器滤波过程用差分方程运算完成
- 简单的TCP连接(send/recv使用的sockfd)
- 6.Spark Streaming:输入DStream和Receiver详解
- CAS 与乐观锁
- Lintcode73 Construct Binary Tree from Preorder and Inorder Traversal solution 题解
- bzoj1034: [ZJOI2008]泡泡堂BNB
- C++ 日期 & 时间
- java抽象类
- Lua 任意类型的get/set方法
- acos
- 【剑指Offer_在线编程】 【牛客网22题:二叉搜索树的后序遍历序列】
- StackOverflow和OutOfMemory
- poj1416——Shredding Company