Construct Binary Tree from Preorder and Postorder Traversal
Return any binary tree that matches the given preorder and postorder traversals.
Values in the traversals pre and post are distinct positive integers.
Example 1:
Input: pre = [1,2,4,5,3,6,7], post = [4,5,2,6,7,3,1]
Output: [1,2,3,4,5,6,7]
Note:
- 1 <= pre.length == post.length <= 30
- pre[] and post[] are both permutations of 1, 2, ..., pre.length.
- It is guaranteed an answer exists. If there exists multiple answers, you can return any of them.
Solution:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
// Input: pre = [1,2,4,5,3,6,7], post = [4,5,2,6,7,3,1]
// Output: [1,2,3,4,5,6,7]
public TreeNode constructFromPrePost(int[] pre, int[] post) {
// System.out.println(Arrays.toString(pre) + ", " + Arrays.toString(post));
if (pre.length == 0) return null;
if (pre.length == 1) return new TreeNode(pre[0]);
int[] postMap = new int[31];
for (int i = 0; i < post.length; i ++) {
postMap[post[i]] = i;
}
TreeNode root = new TreeNode(pre[0]);
int leftLen = postMap[pre[1]] + 1;
root.left = constructFromPrePost(Arrays.copyOfRange(pre, 1, leftLen + 1), Arrays.copyOfRange(post, 0, leftLen));
root.right = constructFromPrePost(Arrays.copyOfRange(pre, 1 + leftLen, pre.length), Arrays.copyOfRange(post, leftLen, post.length - 1));
return root;
}
}