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
Example 1:
Input : {5,2,13} 5 / \ 2 13 Output : {18,20,13} 18 / \ 20 13
Example 2:
Input : {5,3,15} 5 / \ 3 15 Output : {20,23,15} 20 / \ 23 15
/** * Definition of TreeNode: * public class TreeNode { * public int val; * public TreeNode left, right; * public TreeNode(int val) { * this.val = val; * this.left = this.right = null; * } * } */ public class Solution { /** * @param root: the root of binary tree * @return: the new root */ public TreeNode convertBST(TreeNode root) { // write your code here int[] sum = new int[]{0}; helper(root, sum); return root; } private void helper(TreeNode root, int[] sum) { if (root == null) { return; } helper(root.right, sum); sum[0] += root.val; root.val = sum[0]; helper(root.left, sum); } }
来源:https://www.cnblogs.com/xuanlu/p/12549881.html