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
- The number of nodes in the tree is in the range
[0, 10^4]. -10^4 <= Node.val <= 10^4- All the values in the tree are unique.
rootis guaranteed to be a valid binary search tree.
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
- ✓Full worked approach
- ✓Reference code in 5 languages
- ✓Problem-solving tips
- ✓Step-by-step animated visualization
More Tree / Recursion problems
- Balanced Binary TreeEASY
- Binary Tree CamerasHARD
- Binary Tree Inorder TraversalEASY
- Binary Tree Maximum Path SumHARD
- Binary Tree PathsEASY
- Binary Tree Postorder TraversalEASY
- Binary Tree Preorder TraversalEASY
- House Robber IIIMEDIUM
- Construct Binary Tree from Inorder and Postorder TraversalMEDIUM
- Construct Binary Tree from Preorder and Inorder TraversalMEDIUM
- Count Complete Tree NodesEASY
- Count Good Nodes in Binary TreeMEDIUM