[LC] 270. Closest Binary Search Tree Value
Posted xuanlu
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LC] 270. 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
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public int closestValue(TreeNode root, double target) { if (root == null) { return -1; } int res = root.val; while (root != null) { if (Math.abs(root.val - target) < Math.abs(res - target)) { res = root.val; } if (root.val > target) { root = root.left; } else { root = root.right; } } return res; } }
以上是关于[LC] 270. Closest Binary Search Tree Value的主要内容,如果未能解决你的问题,请参考以下文章
270. Closest Binary Search Tree Value
Leetcode 270. Closest Binary Search Tree Value
Leetcode 270: Closest Binary Search Tree Value
270. Closest Binary Search Tree Value - Easy