Binary Trees Building and serializing
381. Construct Binary Tree from Inorder and Postorder Traversal
You are given two integer arrays, inorder and postorder. They are the inorder and the postorder traversal of
the same binary tree. Build that tree and return its root.
An inorder traversal lists the left subtree in inorder, then the node, then the right subtree in inorder. A postorder traversal lists the left subtree in postorder, then the right subtree in postorder, then the node. All the values in the tree are distinct.
The output shows the tree you return level by level, from left to right, with null where a child is missing.
So [5,8,null,3] is the root 5 with a left child 8 and no right child, and 8 has a left child 3. The missing
children after the last node are left out.
Example 1
Input: inorder = [4, -1, 7, 10, 2, -6]
postorder = [-1, 7, 4, 2, -6, 10]
[10,4,-6,null,7,2,null,-1]Explanation: The tree has the root 10. Its left child 4 has a right child 7, and 7 has a left child -1. Its right child -6 has a left child 2. Listing left, node, right from the root gives 4, -1, 7, 10, 2, -6, and listing left, right, node gives -1, 7, 4, 2, -6, 10.
Example 2
Input: inorder = [1000000000], postorder = [1000000000]
[1000000000]Explanation: One value, so the tree is a single node.
Example 3
Input: inorder = [2, 3, 5], postorder = [3, 5, 2]
[2,null,5,3]Explanation: The root 2 has a right child 5, and 5 has a left child 3. The root has no left child, so the output shows
null in its place.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
1 ≤ inorder.length ≤ 105postorder.length == inorder.length-109 ≤ inorder[i], postorder[i] ≤ 109- All the values are distinct.
inorderandpostorderare the inorder and postorder traversals of one binary tree.- That tree has at most 1000 levels.
Clarifying questions
What you would ask an interviewer before writing any code.