Convert BST to Greater Tree — LeetCode 538 Python Solution
- Problem
- #538
- Pattern
- Tree Traversal
- Reading time
- 4 min
- Source
- leetcode.com
The problem
Given the root of a Binary Search Tree (BST), convert it to a Greater Tree such 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 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.
Example
- 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]
Python solution
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def convertBST(self, root: TreeNode) -> TreeNode:
def dfs(root):
nonlocal s
if root is None:
return
dfs(root.right)
s += root.val
root.val = s
dfs(root.left)
s = 0
dfs(root)
return rootComplexity
| Measure | Complexity |
|---|---|
| Time | O(V+E) |
| Space | O(V) auxiliary |
Pattern: Tree Traversal
Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 538. Convert BST to Greater Tree is filed here because LeetCode tags it Tree, Binary Tree and Binary Search Tree, which is the vocabulary this hub collects.
The tree traversal guide has the Python template for the pattern and the 225 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 538. Convert BST to Greater Tree?
- LeetCode 538. Convert BST to Greater Tree is rated Medium on LeetCode.
- What is the time complexity of LeetCode 538. Convert BST to Greater Tree?
- The Python solution on this page runs in O(V+E).
- What is the space complexity of LeetCode 538. Convert BST to Greater Tree?
- The Python solution on this page uses O(V) auxiliary space.
- What topics does LeetCode 538. Convert BST to Greater Tree cover?
- LeetCode 538. Convert BST to Greater Tree is tagged Tree, Depth-First Search, Binary Search Tree and Binary Tree on LeetCode.