LeetCode 270. Closest Binary Search Tree Value
2020-05-18 19:19:51 # leetcode

Problem

LeetCode 270. Closest Binary Search Tree Value

1. 题目简述

给出一颗二叉树,给出一个目标double类型的target,找出与其最近的节点值。例如:

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

    4
   / \
  2   5
 / \
1   3

Output: 4

2. 算法思路

中序遍历

这道题和LeetCode 272看起来很像,只不过272是要求k个最接近的数。

这道题只用找一个最接近的数,很简单,直接中序遍历,愿意加一个判断本次和上一次差值不同剪枝条件也可以,我没加。

3. 解法

  1. 中序遍历,用abs函数记录绝对值,closestValue记录最接近的值
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39

/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int closestValue(TreeNode root, double target) {
double abs = Double.MAX_VALUE;
int closestValue = 0;

while (root != null) {
double diff = target - (double)root.val;
if (Math.abs(diff) < abs) {
closestValue = root.val;
abs = Math.abs(diff);
}
if (diff > 0) {
root = root.right;
} else if (diff < 0) {
root = root.left;
} else {
return root.val;
}
}

return closestValue;
}
}