GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — leetcode-3/problems/src/tree/PostorderToBT.java at master · abcdvemm/leetcode-3 Expand file tree/ Copy pathPostorderToBT.javaMore file actions 73 lines (59 loc) · 1.62 KB / Copy pathPostorderToBT.javaFile metadata and controls73 lines (59 loc) · 1.62 KB 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 package tree; import java.util.HashMap; import java.util.Map; /** * Created by gouthamvidyapradhan on 23/02/2017. Given inorder and postorder traversal of a tree, * construct the binary tree. * * <p>Note: You may assume that duplicates do not exist in the tree. */ public class PostorderToBT { private Map<Integer, Integer> INDEX = new HashMap<>(); private static int postIndex; public class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } } /** * Main method * * @param args * @throws Exception */ public static void main(String[] args) throws Exception { int in[] = new int[] {1, 2}; int post[] = new int[] {1, 2}; TreeNode root = new PostorderToBT().buildTree(in, post); new PostorderToBT().preorderPrint(root); } public TreeNode buildTree(int[] inorder, int[] postorder) { int count = 0; for (int i : inorder) INDEX.put(i, count++); postIndex = postorder.length - 1; return build(0, inorder.length - 1, postorder); } private void preorderPrint(TreeNode root) { if (root != null) { System.out.print(root.val + " "); preorderPrint(root.left); preorderPrint(root.right); } } private TreeNode build(int s, int e, int[] postorder) { if (postIndex >= 0 && s <= e) { int poi = postorder[postIndex]; int ini = INDEX.get(poi); TreeNode node = new TreeNode(poi); postIndex--; if (s == e) return node; // leaf node node.right = build(ini + 1, e, postorder); node.left = build(s, ini - 1, postorder); return node; } return null; } } |
| You are visitor 01402792 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |