AAlgoLoopSpaced repetition for LeetCode
MEDIUMTree / RecursionLeetCode ↗

Convert BST to Greater Tree

The key idea

A reverse in-order walk of a BST (right, node, left) visits keys from largest to smallest. Carry a running sum of everything seen so far; add it to each node before moving on, so every node receives the total of all greater keys.

Problem

You are given the root of a Binary Search Tree (BST). Convert it to a Greater Tree so that every key of the original BST is changed to the original key plus the sum of all keys greater than the original key in the BST.

As a reminder, a binary search tree is a tree that satisfies these constraints: the left subtree of a node contains only nodes with keys less than the node's key, the right subtree of a node contains only nodes with keys greater than the node's key, and both the left and right subtrees must also be binary search trees.

Constraints

Examples

Input: root = [4,1,6,0,2,5,7,null,null,null,3,null,null,null,8] Output: [30,36,21,36,35,26,15,null,null,null,33,null,null,null,8]
Input: root = [0,null,1] Output: [1,null,1]
Input: root = [1,0,2] Output: [3,3,2]

Complexity

Time: O(n) Space: O(n)

See the full solution

410310
Step-by-step visualization
Start free →

More Tree / Recursion problems