You are given two arrays representing the preorder
and postorder
traversals of a binary tree with unique values. Your task is to reconstruct the binary tree from these traversals and return its root.
If multiple valid trees exist, you can return any one of them.
Implement a function that reconstructs the binary tree given:
preorder
: an array of integers representing the preorder traversal.postorder
: an array of integers representing the postorder traversal.Input:
"preorder": [1, 2, 4, 5, 3, 6, 7],
"postorder": [4, 5, 2, 6, 7, 3, 1]
Output:
[1,2,3,4,5,6,7]
Test Case 2
Input:
"preorder": [10, 20, 40, 50, 30, 60],
"postorder": [40, 50, 20, 60, 30, 10]
OUTPUT:
[10,20,30,40,50,60]
preorder
are unique.postorder
is a permutation of preorder
and represents the postorder traversal of the same tree.preorder
is the root of the tree.postorder
is also the root.preorder
(after the root) to determine the boundary of the left subtree in postorder
.Loading component...
Loading component...
Main Function is not defined.
Input: "preorder": [1, 2, 4, 5, 3, 6, 7], "postorder": [4, 5, 2, 6, 7, 3, 1]
OUTPUT: [1,2,3,4,5,6,7]
public static TreeNode constructFromPrePost(int[] pre, int[] post) {
Return_variable = helper(pre, 0, pre.length - 1, post, 0, post.length - 1);
return Return_variable;
}//function end
private static TreeNode helper(int[] pre, int preStart, int preEnd, int[] post, int postStart, int postEnd) {
private TreeNode helper(int[] pre, int preStart, int preEnd, int[] post, int postStart, int postEnd) {
if (preStart > preEnd){
return null;
}//If End
TreeNode root = new TreeNode(pre[preStart]);
if (preStart == preEnd) {
return root;
}//If End
int leftRootVal = pre[preStart + 1];
int index = postStart;
while (post[index] != leftRootVal) {
index++;
}//Loop End
int leftSize = index - postStart + 1;
root.left = helper(pre, preStart + 1, preStart + leftSize, post, postStart, index);
root.right = helper(pre, preStart + leftSize + 1, preEnd, post, index + 1, postEnd - 1);
return root;
}//function end