Problem 437541 · easy · Level 04 Non-Linear Data Structures

Overlay Two Trees

binary tree · recursion

Two maps of the same region are drawn as binary trees; a node's value is the net change in sightings recorded at that spot (it may be negative). Overlay the two maps: wherever both trees have a node the values are added, and wherever only one tree has a node that node is kept as it is. Return the root of the combined tree.

Examples

    4              3                7
   / \            / \              / \
 -1   6   +      5  -6     =      4   0
   \            /     \          / \   \
    2          8       1        8   2   1

Input:  a = build_tree([4, -1, 6, None, 2]), b = build_tree([3, 5, -6, 8, None, None, 1])
Output: tree_to_list(...) == [7, 4, 0, 8, 2, None, 1]
Explanation: 6 + (-6) = 0 is still a node; only missing nodes are taken from the other tree.

Input:  a = build_tree([1]), b = build_tree([])
Output: [1]

Constraints

  • 0 <= number of nodes in each tree <= 1000
  • -1000 <= node.val <= 1000

Goals

  • Recurse over two trees in lockstep
  • Handle the case where only one of the two nodes exists
Starting Python…