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