Note:
You may assume that duplicates do not exist in the tree.
/** * 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) { // By postorder, we can obtain the root node. // By root node, we can divide inorder into two parts. // By the two parts, we can also divide postorder into two parts. // Recursively do this work. if (inorder.length==0 || inorder.length!=postorder.length) return null; int len = inorder.length; // Save <inorder number, inorder index>, so it will be fast to get the index position. Map<Integer, Integer> in = new HashMap<>(); for (int i = 0; i < len; i++) in.put(inorder[i], i); int loIn = 0, hiIn = len-1; int loPost = 0, hiPost = len-1; return genTree(inorder, loIn, hiIn, postorder, loPost, hiPost, in); } private TreeNode genTree(int[] inorder, int loIn, int hiIn, int[] postorder, int loPost, int hiPost, Map<Integer, Integer> in) { if (loIn > hiIn) return null; TreeNode node = new TreeNode(postorder[hiPost]); int id = in.get(postorder[hiPost]); // New 'hiPost' = 'loPost' + ('hiIn' - 'loIn') node.left = genTree(inorder, loIn, id-1, postorder, loPost, loPost+id-(loIn+1), in); node.right = genTree(inorder, id+1, hiIn, postorder, loPost+id-loIn, hiPost-1, in); return node; } }
No comments:
Post a Comment