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的值,再处理左子树
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode convertBST(TreeNode root) {
int[] sum = new int[1];
convertBST(root, sum);
return root;
}
public void convertBST(TreeNode node, int[] sum) {
if (node == null) {
return;
}
convertBST(node.right, sum);
node.val += sum[0];
sum[0] = node.val;
convertBST(node.left, sum);
}
}
3. Time & Space Complexity
DFS: 时间复杂度O(n), 空间复杂度: O(h)
Last updated
Was this helpful?