【一天一大 lee】二叉搜索树的最小绝对差 (难度:简单) - Day20201012

时间:2022-07-26
本文章向大家介绍【一天一大 lee】二叉搜索树的最小绝对差 (难度:简单) - Day20201012,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

20201012

题目:

给你一棵所有节点为非负值的二叉搜索树,请你计算树中任意两节点的差的绝对值的最小值。

示例:

输入:

   1
    
     3
    /
   2

输出:
1

解释:
最小绝对差为 1,其中 2 和 1 的差的绝对值为 1(或者 2 和 3)。

提示:

  • 树中至少有 2 个节点。

抛砖引玉

思路

二叉搜索树(二叉查找树,二叉排序树):

  • 若它的左子树不空,则左子树上所有结点的值均小于它的根结点的值;
  • 若它的右子树不空,则右子树上所有结点的值均大于它的根结点的值;
  • 它的左、右子树也分别为二叉搜索树

中序遍历二叉搜索树(得到的元素为递增的)

抛砖引玉

深度优先遍历(DFS)

DFS 中序遍历模板:

function dfs(node) {
  if (node == null) return
  if (node.left) dfs(node.left)
  if (node.right) dfs(node.right)
}

记录节点值递增,记录上一个节点,分别与后续节点值求差值,返回遇到的最小数

/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number}
 */
var minDiffInBST = function(root) {
  let _result = Number.MAX_VALUE,
    preNode = null
  function dfs(node) {
    if (node === null) return
    if (node.left) dfs(node.left)
    if (preNode && preNode.val !== null) {
      _result = Math.min(_result, node.val - preNode.val)
    }
    preNode = node
    if (node.right) dfs(node.right)
  }
  dfs(root)
  return _result
}

广度优先搜索(BFS)

BFS 模板:

function(root) {
  if (root == null) return
  let queue = [root]
  while(queue.length){
    let node = queue.pop();
    if(node.left) queue.push(node.left)
    if(node.right) queue.push(node.right)
  }
}

按照上面 BFS 模板遍历为非中序遍历,但是逻辑上即使不是中序遍历,只要完成遍历,我们可以重新对遍历的值排序然后再求值

var minDiffInBST = function(root) {
  let _result = Number.MAX_VALUE,
    list = [],
    queue = [root]
  while (queue.length) {
    let node = queue.pop()
    list.push(node.val)
    if (node.left) queue.push(node.left)
    if (node.right) queue.push(node.right)
  }
  list.sort((a, b) => a - b)
  for (let i = 1; i < list.length; i++) {
    _result = Math.min(_result, list[i] - list[i - 1])
  }
  return _result
}

BFS 中序遍历

var minDiffInBST = function(root) {
  let _result = Number.MAX_VALUE,
    preNode = null,
    queue = []
  while (queue.length > 0 || root) {
    while (root) {
      queue.push(root)
      root = root.left
    }
    root = queue.pop()
    if (preNode && preNode.val !== null) {
      _result = Math.min(_result, root.val - preNode.val)
    }
    preNode = root
    root = root.right
  }
  return _result
}