pwstrick / daily

一份搜集的前端面试题目清单、面试相关以及各类学习的资料(不局限于前端)
2.38k stars 242 forks source link

二叉搜索树节点最小距离 #1041

Open pwstrick opened 4 years ago

pwstrick commented 4 years ago

783. 二叉搜索树节点最小距离

/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number}
 */
var min,
    prev;
var minDiffInBST = function(root) {
    min = Number.MAX_VALUE;
    midOrder(root);
    return min;
};
function midOrder(root) {
    if(root == null)
        return;
    midOrder(root.left);
    if(prev) {
        min = Math.min.call(undefined, min, Math.abs(prev.val - root.val));
    }
    prev = root;
    midOrder(root.right);
}