Javascript Solution


  • 0
    L

    first, we should push the node to an array by looping the tree;then, we can loop the array to calculate the min count;

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

Log in to reply
 

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