https://leetcode.com/problems/convert-bst-to-greater-tree/#/description
题目思路:
题目给了一个二叉搜索树,需要我们进行转换,改变二叉树每个值。值等于其本身再加上原二叉树中比所有它大的节点值。由于BST二叉树root.left.val < root.val < root.left.val,所有我们可以从最右边的值开始遍历,用sum值把遍历过的值的和。基于此种遍历方式,先遍历的值一定比后遍历的值大,所以每次只要把正在遍历的节点的值和sum相加,再作为改变后的节点值即可。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
int sum = 0;
public TreeNode convertBST(TreeNode root) {
convert(root);
return root;
}
public void convert(TreeNode root) {
if(root == null)
return;
convertBST(root.right);
sum += root.val;
root.val = sum;
convertBST(root.left);
}
}