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); }