538 Convert BST to Greater Tree

1. Question

Given 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 sum of all keys greater than the original key in BST.

Example:

Input:
 The root of a Binary Search Tree like this:
              5
            /   \
           2     13


Output:
 The root of a Greater Tree like this:
             18
            /   \
          20     13

2. Implementation

(1) DFS

思路: 规律比较明显,对于每个node,先处理右子树,累加右子树的和,然后更新当前node的值,再处理左子树

3. Time & Space Complexity

DFS: 时间复杂度O(n), 空间复杂度: O(h)

Last updated

Was this helpful?