JavaScript O(n) Solution non-recursion


  • 0
    var getMinimumDifference = function(root) {
      let pre = undefined;
      let diff = Infinity;
      var stack = [];
      let curNode = root;
      stack.push(root);
      while(curNode.left) {
        curNode = curNode.left;
        stack.push(curNode);
      }
      while(stack.length !== 0) {
        curNode = stack.pop();
        if (pre !== undefined && diff > curNode.val - pre) {
          diff = curNode.val - pre;
        }
        pre = curNode.val;
        if (curNode.right) {
          curNode = curNode.right;
          stack.push(curNode);
          while(curNode.left) {
            curNode = curNode.left;
            stack.push(curNode);
          }
        }
      }
      return diff;
    }

Log in to reply
 

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