Problem 488337 · medium · Level 04 Non-Linear Data Structures

Replace Values With Sums of Larger Values

binary search tree · recursion · reverse inorder

A binary search tree holds distinct scores. Rewrite the tree in place so that every node's value becomes the sum of its own score and every larger score in the tree. Return the root.

Examples

        10                       44
       /  \                     /  \
      5    14                 62    34
     / \     \     ==>        / \     \
    2   7     20            64   51    20
       /                        /
      6                       57

Input:  root = build_tree([10, 5, 14, 2, 7, None, 20, None, None, 6])
Output: tree_to_list(...) == [44, 62, 34, 64, 51, None, 20, None, None, 57]

Input:  root = build_tree([2, 1, 3])
Output: [5, 6, 3]

The tests also use rewritten_original(root): it calls greater_sum_tree(root) and returns tree_to_list(root) of the tree you were given, so building a new tree instead of changing the values in place fails.

Goals

  • Traverse a search tree in descending order (right, node, left)
  • Carry a running total through the traversal
Starting Python…