Letcode 1038. Binary Search Tree to Greater Sum Tree An Easy-to-understand C++ Solution

Sdílet
Vložit
  • čas přidán 27. 06. 2024
  • In this video i have solved leetcode-1038 Problem named Binary Search Tree to Greater Sum Tree.
    In this Question the intuition to solve this problem comes from the problem statement only "the original BST is changed to the original key plus the sum of all keys greater than the original key in BST."
    We solve it in 3 steps.
    1. As you want to find the sum of all value greater than your current node that means you have to always go to current node's right as their only you can find values greater than it's node value the given tree is a BST.
    2. After that when your right call get completed then compute your
    Sum += node--val;
    3. Now replace the original node value with the sum that you have calculated.
    root--val = sum;
    4. Now make call for left node.
    Time Complexity (TC):
    The time complexity of this solution is O(N), where N is the number of nodes in the Binary Search Tree (BST).
    The reason is that we are traversing the entire tree once, visiting each node exactly once. The recursive calls to the solve function ensure that we visit all the nodes in the right-to-left in-order traversal.
    Space Complexity (SC):
    The space complexity of this solution is O(H), where H is the height of the BST.
    The reason is that the recursion stack in the solve function will have a depth of at most the height of the BST. In the worst case, when the BST is skewed (i.e., a linked list-like structure), the height of the BST will be N, and the space complexity will be O(N).
    However, in a balanced BST, the height will be approximately log(N), and the space complexity will be O(log(N)).
    The only additional space used is the sum variable, which is a constant extra space.
    So, in summary:
    Time Complexity: O(N)
    Space Complexity: O(H), where H is the height of the BST

Komentáře •