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.code
Time Complexity
O(N)
Space Complexity
O(1)it
一看到BST,直接能够想到中序遍历了,这题和普通中序遍历不一样的地方在于,由于它要把整颗树中比本身大的点加起来,对于BST中的点,比本身大的点只有多是本身右边的点,分治法先找到右边最大的,keep一个global的sum,从右开始作的特殊的中序遍历到的每个点的值都是本身自己加上以前遍历过的全部点的和。io
private int sum = 0; public TreeNode convertBST(TreeNode root) { // Write your code here if(root == null) return null; helper(root); return root; } private void helper(TreeNode root){ if(root == null) return; helper(root.right); root.val += sum; sum = root.val; helper(root.left); }