Intuition
This problem is very important and fundamental for the understanding of how Binary Search Trees work because it leverages on a BST feature.
We are required to replace each node’s val with the it’s own value plus sum of all values greater than it.
In a BST, all values on the right are greater than the values on the left. This makes coming to a solution easy, now we just have to sum up all right values, set the node’s value and call the same function on the left nodes.
Note: this problem is duplicated in 538 Convert BST to Greater Tree
Code
Python3
Big O Analysis
-
Runtime
The runtime complexity here is since we would be visiting all nodes in the tree.
-
Memory
The memory usage is since we are not using any extra data structure.
— A