Medium
,Tree
,Array
,Hash Table
,Divide and Conquer
106. Construct Binary Tree from Inorder and Postorder Traversal
Given two integer arrays inorder
and postorder
where inorder
is the inorder traversal of a binary tree and postorder
is the postorder traversal of the same tree, construct and return the binary tree.
Example 1:
Input: inorder = [9,3,15,20,7], postorder = [9,15,7,20,3]
Output: [3,9,20,null,null,15,7]
Example 2:
Input: inorder = [-1], postorder = [-1]
Output: [-1]
Constraints:
inorder.length
<= 3000postorder.length
== inorder.length
inorder[i]
, postorder[i]
<= 3000inorder
and postorder
consist of unique values.postorder
also appears in inorder
.inorder
is guaranteed to be the inorder traversal of the tree.postorder
is guaranteed to be the postorder traversal of the tree.class Solution:
def buildTree(self, inorder: List[int], postorder: List[int]) -> Optional[TreeNode]:
idx_map = {val:idx for idx, val in enumerate(inorder)}
def recur(low, high):
if low > high:
return
idx = idx_map[postorder.pop()]
root = TreeNode(inorder[idx])
root.right = recur(idx + 1, high)
root.left = recur(low, idx - 1)
return root
return recur(0, len(inorder) - 1)
Ron Chen Thu, Mar 16, 2023
function buildTree(inorder, postorder) {
const root = postorder[postorder.length - 1];
const rootIndex = inorder.indexOf(root);
const leftInorder = inorder.slice(0, rootIndex);
const rightInorder = inorder.slice(rootIndex + 1);
const leftPostorder = postorder.slice(0, leftInorder.length);
const rightPostorder = postorder.slice(leftInorder.length, postorder.length - 1);
const tree = new TreeNode(root);
if (leftInorder.length > 0) {
tree.left = buildTree(leftInorder, leftPostorder);
}
if (rightInorder.length > 0) {
tree.right = buildTree(rightInorder, rightPostorder);
}
return tree;
}
MarsgoatMar 17, 2023