Sign in to devexcode.com with google.com

To continue, google.com will share your name, email address, and profile picture with this site. See this site's privacy policy.

538. Convert BST to Greater Tree

Explanation

To convert a Binary Search Tree (BST) to a Greater Tree, we can perform a reverse in-order traversal of the tree. In a reverse in-order traversal, we visit nodes in the right subtree first, followed by the current node, and then the left subtree. During this traversal, we keep track of the running sum of nodes visited so far. At each node, we update its value by adding the running sum to it.

Algorithm:

  1. Initialize a variable sum to keep track of the running sum.
  2. Perform a reverse in-order traversal of the BST.
  3. For each node visited:
    • Update the node's value by adding sum to it.
    • Update sum by adding the node's value to it.
  4. Return the modified root of the BST.

Time Complexity: O(n) - where n is the number of nodes in the BST. Space Complexity: O(h) - where h is the height of the BST.

class Solution {
    int sum = 0;

    public TreeNode convertBST(TreeNode root) {
        if (root != null) {
            convertBST(root.right);
            sum += root.val;
            root.val = sum;
            convertBST(root.left);
        }
        return root;
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.