|
| 1 | +// Problem Number: 889 |
| 2 | + |
| 3 | +// Construct Binary Tree From Preorder and PostOrder Traversal |
| 4 | + |
| 5 | +/** |
| 6 | + * Definition for a binary tree node. |
| 7 | + * public class TreeNode { |
| 8 | + * int val; |
| 9 | + * TreeNode left; |
| 10 | + * TreeNode right; |
| 11 | + * TreeNode() {} |
| 12 | + * TreeNode(int val) { this.val = val; } |
| 13 | + * TreeNode(int val, TreeNode left, TreeNode right) { |
| 14 | + * this.val = val; |
| 15 | + * this.left = left; |
| 16 | + * this.right = right; |
| 17 | + * } |
| 18 | + * } |
| 19 | + */ |
| 20 | +class Solution { |
| 21 | + public TreeNode constructFromPrePost(int[] pre, int[] post) { |
| 22 | + Map<Integer, Integer> postToIndex = new HashMap<>(); |
| 23 | + |
| 24 | + for (int i = 0; i < post.length; ++i) |
| 25 | + postToIndex.put(post[i], i); |
| 26 | + |
| 27 | + return build(pre, 0, pre.length - 1, post, 0, post.length - 1, postToIndex); |
| 28 | + } |
| 29 | + |
| 30 | + private TreeNode build(int[] pre, int preStart, int preEnd, int[] post, int postStart, |
| 31 | + int postEnd, Map<Integer, Integer> postToIndex) { |
| 32 | + if (preStart > preEnd) |
| 33 | + return null; |
| 34 | + if (preStart == preEnd) |
| 35 | + return new TreeNode(pre[preStart]); |
| 36 | + |
| 37 | + final int rootVal = pre[preStart]; |
| 38 | + final int leftRootVal = pre[preStart + 1]; |
| 39 | + final int leftRootPostIndex = postToIndex.get(leftRootVal); |
| 40 | + final int leftSize = leftRootPostIndex - postStart + 1; |
| 41 | + |
| 42 | + TreeNode root = new TreeNode(rootVal); |
| 43 | + root.left = build(pre, preStart + 1, preStart + leftSize, post, postStart, leftRootPostIndex, |
| 44 | + postToIndex); |
| 45 | + root.right = build(pre, preStart + leftSize + 1, preEnd, post, leftRootPostIndex + 1, |
| 46 | + postEnd - 1, postToIndex); |
| 47 | + return root; |
| 48 | + } |
| 49 | +} |
0 commit comments