
Sponsored
Sponsored
This approach leverages the property of Binary Search Trees where the nodes in the right subtree are greater than those in the left subtree. By performing a reverse inorder traversal (right -> root -> left), we can accumulate the sum of all nodes greater than the current node and update each node with this accumulated sum. The traversal ensures that we always process the greater nodes first.
Time Complexity: O(n), where n is the number of nodes in the BST, since we visit each node exactly once.
Space Complexity: O(h), where h is the height of the tree, due to the recursion stack used during traversal.
1class TreeNode:
2 def __init__(self, val=0, left=None, right=None):
3 self.val = val
4 self.left = left
5 self.right = right
6
7class Solution:
8 def __init__(self):
9 self.sum = 0
10
11 def convertBST(self, root: TreeNode) -> TreeNode:
12 if root:
13 self.convertBST(root.right)
14 self.sum += root.val
15 root.val = self.sum
16 self.convertBST(root.left)
17 return rootThe Python solution uses a Solution class to encapsulate a sum attribute that keeps track of the accumulated value during traversal. The method convertBST updates the tree by performing a reverse inorder traversal.
The Morris Traversal technique allows in-order traversal of a binary tree without using extra space for recursion or a stack. It modifies the tree structure during the traversal, and at the end of the traversal, the original tree structure is restored.
For this problem, we adapt the Morris Traversal to traverse the tree in reverse inorder fashion and keep track of the sum of nodes greater than the current node.
Time Complexity: O(n), where n is the number of nodes. Although every edge is visited at most twice, the overall complexity remains linear.
Space Complexity: O(1) since no extra space is used apart from variables.
1class TreeNode:
2 def __init__(self, val=0,
This Python solution uses the Morris Traversal technique, which allows modifying the tree without using stack or recursion explicitly. The key idea is to establish a temporary link between each node and its inorder predecessor, traverse in reverse inorder, update the nodes, and then restore the tree structure by removing the temporary links.