【LeetCode】270. Closest Binary Search Tree Value 解题报告(C++)


题目地址:https://leetcode-cn.com/problems/closest-binary-search-tree-value/

题目描述

Given a non-empty binary search tree and a target value, find the value in the BST that is closest to the target.

Note:

  • Given target value is a floating point.
  • You are guaranteed to have only one unique value in the BST that is closest to the target.

Example:

Input: root = [4,2,5,1,3], target = 3.714286

    4
   / \
  2   5
 / \
1   3

Output: 4

题目大意

给定一个不为空的二叉搜索树和一个目标值 target,请在该二叉搜索树中找到最接近目标值 target 的数值。

解题方法

递归

根据BST的特点,我们根据target和当前节点的大小进行判断,是向左还是向右继续查找,和BST中查找一个节点的方法是一样的,不过这个题要返回最接近的节点,所以我使用了两个值:value和minDist,分别保存最接近的值和差距绝对值,并且使用了引用方式传递,可以直接原地修改。

C++代码如下:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int closestValue(TreeNode* root, double target) {
        int value = 0;
        double minDist = LONG_MAX;
        minDistance(root, target, value, minDist);
        return value;
    }
    void minDistance(TreeNode* root, double target, int& value, double& minDist) {
        if (!root) return;
        int number = root->val;
        double distance = fabs(target - number);
        if (distance < minDist) {
            value = number;
            minDist = distance;
        }
        if (number > target) {
            minDistance(root->left, target, value, minDist);
        } else {
            minDistance(root->right, target, value, minDist);
        }
    }
};

日期

2019 年 9 月 17 日 —— 听了hulu宣讲会,觉得hulu的压力不大

posted @ 2019-09-17 19:39  负雪明烛  阅读(27)  评论(0编辑  收藏  举报