I came up with a similar solution, and it passed the tests:
defmodule Solution do
@spec convert_bst(root :: TreeNode.t | nil) :: TreeNode.t | nil
def convert_bst(root) do
{converted, _} = do_convert_bst(root, 0)
converted
end
defp do_convert_bst(nil, _carry), do: {nil, 0}
defp do_convert_bst(node, carry) do
{right, sum_r} = do_convert_bst(node.right, carry)
carry = carry + node.val + sum_r
{left, sum_l} = do_convert_bst(node.left, carry)
{%TreeNode{left: left, right: right, val: carry}, node.val + sum_l + sum_r}
end
end
carry is the sum of the values of all the nodes that have already been visited that have values greater than the next node to visit.






















