Skip to content

530.二叉搜索树的最小绝对差

题解

js
/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number}
 */

var getMinimumDifference = function (root) {
  var pre;
  var min = Number.MAX_VALUE;
  function dfs(root) {
    if (!root) return;
    dfs(root.left); // 左
    if (pre != null) {
      // 当前值 - 上次的值 求最小差
      min = Math.min(min, root.val - pre);
    }
    pre = root.val; // 记录上一次的值
    dfs(root.right); // 右
  }
  dfs(root);
  return min;
};
/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number}
 */

var getMinimumDifference = function (root) {
  var pre;
  var min = Number.MAX_VALUE;
  function dfs(root) {
    if (!root) return;
    dfs(root.left); // 左
    if (pre != null) {
      // 当前值 - 上次的值 求最小差
      min = Math.min(min, root.val - pre);
    }
    pre = root.val; // 记录上一次的值
    dfs(root.right); // 右
  }
  dfs(root);
  return min;
};