|
| 1 | +import java.util.Arrays; |
| 2 | +import java.util.HashMap; |
| 3 | + |
| 4 | +/** |
| 5 | + * Given preorder and inorder traversal of a tree, construct the binary tree. |
| 6 | + * in-order: left, root, right |
| 7 | + * pre-order: root, left, right |
| 8 | + * <p/> |
| 9 | + * <p/> |
| 10 | + * ________ 7______ |
| 11 | + * / \ |
| 12 | + * __10__ ___2 |
| 13 | + * / \ / |
| 14 | + * 4 3 _8 |
| 15 | + * \ / |
| 16 | + * 1 11 |
| 17 | + * preorder = {7,10,4,3,1,2,8,11} |
| 18 | + * inorder = {4,10,3,1,7,11,8,2} |
| 19 | + */ |
| 20 | +public class BuildBT { |
| 21 | + public static void main(String[] args) { |
| 22 | + int[] preorder = new int[]{7, 10, 4, 3, 1, 2, 8, 11}; |
| 23 | + int[] inorder = new int[]{4, 10, 3, 1, 7, 11, 8, 2}; |
| 24 | + |
| 25 | + // build b tree |
| 26 | + Node bt = buildBTInorderPreorder(inorder, preorder); |
| 27 | + bt.printBT(); |
| 28 | + } |
| 29 | + |
| 30 | + public static HashMap<Integer, Integer> mapIndex(int[] inorder) { |
| 31 | + HashMap<Integer, Integer> index = new HashMap<Integer, Integer>(); |
| 32 | + for (int i = 0; i < inorder.length; i++) { |
| 33 | + index.put(inorder[i], i); |
| 34 | + } |
| 35 | + return index; |
| 36 | + } |
| 37 | + |
| 38 | + public static Node buildBTInorderPreorder(int[] in, |
| 39 | + int[] pre) { |
| 40 | + if (in.length == 0 || pre.length != in.length) |
| 41 | + return null; |
| 42 | + |
| 43 | + HashMap<Integer, Integer> index = new HashMap<Integer, Integer>(); |
| 44 | + for (int i = 0; i < in.length; i++) { |
| 45 | + index.put(in[i], i); |
| 46 | + } |
| 47 | + |
| 48 | + Node root = new Node(pre[0]); |
| 49 | + int rootIndex = index.get(pre[0]); |
| 50 | + root.left = buildBTInorderPreorder(Arrays.copyOfRange(in, 0, rootIndex), |
| 51 | + Arrays.copyOfRange(pre, 1, rootIndex+1)); |
| 52 | + root.right = buildBTInorderPreorder(Arrays.copyOfRange(in, rootIndex + 1, in.length), |
| 53 | + Arrays.copyOfRange(pre, rootIndex+1, pre.length)); |
| 54 | + return root; |
| 55 | + } |
| 56 | +} |
0 commit comments