Leetcode 538: Convert BST to Greater Tree

grid47
grid47
Exploring patterns and algorithms
Sep 14, 2024 5 min read

A binary search tree where each node is gradually updated to a greater tree, with each transformation softly highlighted.
Solution to LeetCode 538: Convert BST to Greater Tree Problem

Given the root of a Binary Search Tree (BST), convert it into a Greater Tree where every node’s value is replaced by the sum of all greater node values in the BST plus its original value.
Problem
Approach
Steps
Complexity
Input: Each input consists of a binary search tree represented by its root. The nodes of the tree contain integer values.
Example: Input: root = [5, 2, 13]
Constraints:
• The number of nodes in the tree is in the range [0, 10^4].
• Each node value is an integer within the range [-10^4, 10^4].
• All node values are unique.
Output: Return the root of the binary search tree after transforming it into the Greater Tree.
Example: Output: [18, 20, 13]
Constraints:
• The output should be a valid Binary Search Tree where each node’s value is the sum of all greater node values plus its original value.
Goal: Transform the BST into a Greater Tree by updating each node's value.
Steps:
• Perform a reverse inorder traversal (right, node, left) to access nodes in descending order.
• Accumulate the sum of node values greater than the current node’s value.
• Update the current node's value by adding the accumulated sum.
Goal: The input tree must be a valid binary search tree (BST) with unique values.
Steps:
• The tree is a valid BST.
• The values of the nodes are unique.
• The tree contains between 0 and 10^4 nodes.
Assumptions:
• The input tree is a valid Binary Search Tree.
Input: Input: root = [5, 2, 13]
Explanation: In this example, after transforming the BST into a Greater Tree, the node with value 5 becomes 18, the node with value 2 becomes 20, and the node with value 13 stays the same.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus