首页 > 代码库 > [LeetCode]106 Construct Binary Tree from Inorder and Postorder Traversal
[LeetCode]106 Construct Binary Tree from Inorder and Postorder Traversal
https://oj.leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/
http://blog.csdn.net/linhuanmars/article/details/24390157
/** * Definition for binary tree * 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 || inorder.length == 0 || postorder == null || postorder.length == 0 || inorder.length != postorder.length) return null; Map<Integer, Integer> inorderMap = new HashMap<>(); for (int i = 0 ; i < inorder.length ; i ++) { inorderMap.put(inorder[i], i); } return build(0, inorder.length - 1, postorder, 0, postorder.length - 1, inorderMap); } private TreeNode build(int inStart, int inEnd, int[] postorder, int postStart, int postEnd, Map<Integer, Integer> inorderMap) { if(inStart > inEnd || postStart > postEnd) return null; int rootValue = postorder[postEnd]; TreeNode root = new TreeNode(rootValue); int k = inorderMap.get(rootValue); // From the post-order array, we know that last element is the root. We can find the root in in-order array. Then we can identify the left and right sub-trees of the root from in-order array. // !!! Using the length of left sub-tree, we can identify left and right sub-trees in post-order array. Recursively, we can build up the tree. int rightnodes = inEnd - k; // how many nodes on the right of k; root.right = build(k+1, inEnd, postorder, postEnd - 1 - rightnodes + 1, postEnd - 1, inorderMap); root.left = build(inStart, k-1, postorder, postStart, postEnd - 1 - rightnodes, inorderMap); // Becuase k is not the length, it it need to -(inStart+1) to get the length return root; } }
[LeetCode]106 Construct Binary Tree from Inorder and Postorder Traversal
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。