538. Convert BST to Greater Tree

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.

 

//本解法是反中序遍历所有节点,即右中左的顺序

class Solution {
    int sum = 0;
    public TreeNode convertBST(TreeNode root) {
       convert(root);
       return root;
    }
    public void convert(TreeNode node) {
       if (node == null) return;
       convert(node.right);
       node.val += sum;
       sum = node.val;
       convert(node.left);
    }
}

 

posted @ 2023-03-16 19:20  MarkLeeBYR  阅读(12)  评论(0编辑  收藏  举报