Convert BST to Greater Tree

http://www.lintcode.com/zh-cn/problem/convert-bst-to-greater-tree/

public class Solution {
    private int sum = 0;

    /*
     * @param root: the root of binary tree
     * @return: the new root
     */
    public TreeNode convertBST(TreeNode root) {
        // write your code here
//        使用递归,树的操作使用递归会极大简化
//        我们考虑对于每个节点来说,必须先遍历右边的节点
//        因为右边的节点最大,根节点和左节点需要加
//        然后是遍历根节点,最后遍历左节点
//        遍历过程中我们需要把当前的值都记录下来,累加上。
        tree(root);
        return root;
    }

    private void tree(TreeNode root) {
        if (root == null) {
            return;
        }
        tree(root.right);
        sum += root.val;
        root.val = sum;
        tree(root.left);
    }
}

你可能感兴趣的:(Convert BST to Greater Tree)