106. Construct Binary Tree from Inorder and Postorder Traversal
Problem
Rebuild a binary tree from its inorder and postorder traversals (all values are unique) and return the root.
Example: inorder = [9,3,15,20,7], postorder = [9,15,7,20,3] → [3,9,20,null,null,15,7]
Mirror of 105: the last postorder element is the root. Consume postorder from the end and build the right subtree first.
Complexity: O(n).
class Solution:
def buildTree(self, inorder: List[int], postorder: List[int]) -> Optional[TreeNode]:
pos = {v: i for i, v in enumerate(inorder)}
def build(lo, hi):
if lo >= hi:
return None
root = TreeNode(postorder.pop())
m = pos[root.val]
root.right = build(m + 1, hi)
root.left = build(lo, m)
return root
return build(0, len(inorder))
assert tree_vals(Solution().buildTree([9, 3, 15, 20, 7], [9, 15, 7, 20, 3])) == [3, 9, 20, None, None, 15, 7]
assert tree_vals(Solution().buildTree([-1], [-1])) == [-1]
assert tree_vals(Solution().buildTree([2, 1], [2, 1])) == [1, 2]
class Solution {
private int post;
private final Map<Integer, Integer> pos = new HashMap<>();
public TreeNode buildTree(int[] inorder, int[] postorder) {
for (int i = 0; i < inorder.length; i++) pos.put(inorder[i], i);
post = postorder.length - 1;
return build(postorder, 0, inorder.length);
}
private TreeNode build(int[] postorder, int lo, int hi) {
if (lo >= hi) return null;
TreeNode root = new TreeNode(postorder[post--]);
int m = pos.get(root.val);
root.right = build(postorder, m + 1, hi);
root.left = build(postorder, lo, m);
return root;
}
}
func buildTree(inorder []int, postorder []int) *TreeNode {
pos := map[int]int{}
for i, v := range inorder {
pos[v] = i
}
next := len(postorder) - 1 // postorder read backwards: root, right subtree, left subtree
var build func(lo, hi int) *TreeNode
build = func(lo, hi int) *TreeNode {
if lo >= hi {
return nil
}
root := &TreeNode{Val: postorder[next]}
next--
m := pos[root.Val]
root.Right = build(m+1, hi)
root.Left = build(lo, m)
return root
}
return build(0, len(inorder))
}