[Javascript] reversed traversal solution


  • 0
    C

    The logic is to traverse the tree in reverse order (largest value first) and set node values as the suffix sums of nodes visited.

    var convertBST = function(root) {
        var sum = 0;
        
        const reverse = node => {
            if ( !!node ) {
                reverse(node.right);
                node.val += sum;
                sum += node.val - sum;
                reverse(node.left);
            }
            
            return node;
        }
        
        return reverse(root);
    };
    

Log in to reply
 

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