美文网首页
270. Closest Binary Search Tree

270. Closest Binary Search Tree

作者: jluemmmm | 来源:发表于2021-10-01 11:14 被阅读0次

给定BST和目标值,返回 BST中最接近目标的值。

中序遍历 + 线性搜索

  • 时间复杂度O(N),空间复杂度O(N)
  • Runtime: 84 ms, faster than 72.24%
  • Memory Usage: 43.5 MB, less than 8.16%
/**
 * 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
 * @param {number} target
 * @return {number}
 */
var closestValue = function(root, target) {
  let res = [];
  let min = -1;
  let closet = root.val;
  inorder(root, res);
  for (let i = 0; i < res.length; i++) {
    if (min === -1) min = Math.abs(res[i] -target);
    if (Math.abs(res[i] -target) <= min) {
      min = Math.abs(res[i] -target);
      closet = res[i];
    }
  }
  return closet;
};

var inorder = function(root, res) {
  if (!root) return;
  inorder(root.left, res);
  res.push(root.val);
  inorder(root.right, res);
}

二分查找

  • 时间复杂度O(H),空间复杂度O(1)
  • Runtime: 76 ms, faster than 94.08%
  • Memory Usage: 42.6 MB, less than 51.22%
var closestValue = function(root, target) {
  let val = root.val;
  let closet = root.val;
  while (root !== null) {
    val = root.val;
    closet = Math.abs(val - target) < Math.abs(closet - target) ? val : closet;
    root = target < root.val ? root.left : root.right;
  }
  return closet;
};

相关文章

网友评论

      本文标题:270. Closest Binary Search Tree

      本文链接:https://www.haomeiwen.com/subject/ittynltx.html