538. 把二叉搜索树转换为累加树

中序遍历

class Solution {

    int sum = 0;

    public TreeNode convertBST(TreeNode root) {

        inorder(root);
        return root;
    }

    /**
     * 按照右中左的顺序进行中序遍历
     * 对中间的节点进行赋值
     */
    public void inorder(TreeNode root){

        if (root == null){
            return;
        }

        inorder(root.right);

        root.val += sum;
        sum = root.val;

        inorder(root.left);
    }
}

/**
 * 时间复杂度 O(n)
 * 空间复杂度 O(logn)
 */

https://leetcode-cn.com/problems/convert-bst-to-greater-tree/

posted @ 2022-02-24 13:36  振袖秋枫问红叶  阅读(29)  评论(0)    收藏  举报