LeetCode Construct Binary Tree from Inorder and Postorder Traversal
2015-08-21 03:03
423 查看
原题链接在这里:https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/
这道题与Construct Binary Tree from Preorder and Inorder Traversal 思路相似,不同之处在于这里的root在postorder的最有一位,其他都相同,由inorder找出分切点。
Time O(n), Space O(n).
Note:
在recursion调用时postorder的index更新一定会用到(index-inL). 我刚开始很凑巧的写成了postR = index-1, 第一次循
环恰巧相等,但之后就不对了。
AC Java:
这道题与Construct Binary Tree from Preorder and Inorder Traversal 思路相似,不同之处在于这里的root在postorder的最有一位,其他都相同,由inorder找出分切点。
Time O(n), Space O(n).
Note:
在recursion调用时postorder的index更新一定会用到(index-inL). 我刚开始很凑巧的写成了postR = index-1, 第一次循
环恰巧相等,但之后就不对了。
AC Java:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public TreeNode buildTree(int[] inorder, int[] postorder) { if(inorder == null || postorder == null || inorder.length == 0|| postorder.length == 0 || inorder.length != postorder.length){ return null; } HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>(); for(int i = 0; i< inorder.length; i++){ hm.put(inorder[i],i); } return helper(inorder, 0, inorder.length-1, postorder, 0, postorder.length-1, hm); } private TreeNode helper(int[] inorder,int inL,int inR, int[] postorder,int postL,int postR, HashMap<Integer, Integer> hm){ if(inL>inR || postL>postR){ return null; } TreeNode root = new TreeNode(postorder[postR]); int index = hm.get(root.val); root.left = helper(inorder, inL, index-1, postorder, postL, index-inL+postL-1, hm); //error root.right = helper(inorder, index+1, inR, postorder, index-inL+postL, postR-1, hm); return root; } }
相关文章推荐
- LeetCode Construct Binary Tree from Inorder and Postorder Traversal
- hdu 3068 最长回文 【Manacher求最长回文子串,模板题】
- U盘安装centos7
- POJ2186--Popular Cows(Tarjan+缩点)
- 一次SQLSERVER触发器编写感悟
- Git和SSH协议
- LeetCode Construct Binary Tree from Preorder and Inorder Traversal
- LeetCode Construct Binary Tree from Preorder and Inorder Traversal
- 控制反转模式----依赖注入(容器)
- 使用 cscope浏览 C++文件
- VS2015 Android-APP环境的配置
- hibernate的list集合映射(与set区别)
- ZOJ 3674 Search in the Wiki 【C++STL大法尽情地模拟】
- 苦逼啊--qt for android 5.4.1 camera
- [Amazon] Find loop in a singly linkedlist
- 安装CentOS 6.7以及CentOS 7.1
- 黑马程序员——Java基础---继承、抽象、接口(一)
- Java实现多线程的两种方式
- 等价关系
- 最新版Butterknife plugin支持butterknife7.0.1和兼容butterknife 6.1.0及以下