Javascript Solution


  • 0
    L

    first, we should loop the BST and push the node to an array. then, we can to loop the array and increment the array's element.

    /**
     * Definition for a binary tree node.
     * function TreeNode(val) {
     *     this.val = val;
     *     this.left = this.right = null;
     * }
     */
    /**
     * @param {TreeNode} root
     * @return {TreeNode}
     */
    var convertBST = function(root) {
        const arr = loopBST(root);
        let sum = 0;
        for(let i = 0; i < arr.length; i++){
            arr[i].val += sum;
            sum = arr[i].val;
        }
        return root;
    };
    
    function loopBST(root){
        if(!root)
            return [];
        return loopBST(root.right).concat([root], loopBST(root.left));
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.