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[] preorder, int[] inorder) { // By preorder, we can obtain the root node. // By root node, we can divide inorder into two parts. // By the two parts, we can also divide preorder into two parts. // Recursively do this work. if (inorder.length==0 || inorder.length!=preorder.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 loPre = 0, hiPre = len-1; return genTree(inorder, loIn, hiIn, preorder, loPre, hiPre, in); } private TreeNode genTree(int[] inorder, int loIn, int hiIn, int[] preorder, int loPre, int hiPre, Map<Integer, Integer> in) { if (loIn > hiIn) return null; TreeNode node = new TreeNode(preorder[loPre]); int id = in.get(preorder[loPre]); // New 'hiPre' = 'loPre' + ('hiIn' - 'loIn') node.left = genTree(inorder, loIn, id-1, preorder, loPre+1, loPre+id-loIn, in); node.right = genTree(inorder, id+1, hiIn, preorder, loPre+id-loIn+1, hiPre, in); return node; } }
No comments:
Post a Comment