LeetCode 270. Closest Binary Search Tree Value
原题链接在这里:https://leetcode.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.
题解:
target 一定在找的path 上,若是出现了比minDiff 还小的差值,就把改点更新为cloest.
Time Complexity: O(h). h 是树的高度.
Space: O(1).
AC Java:
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode() {} 8 * TreeNode(int val) { this.val = val; } 9 * TreeNode(int val, TreeNode left, TreeNode right) { 10 * this.val = val; 11 * this.left = left; 12 * this.right = right; 13 * } 14 * } 15 */ 16 class Solution { 17 public int closestValue(TreeNode root, double target) { 18 int closest = root.val; 19 while(root != null){ 20 if(Math.abs(root.val - target) < Math.abs(closest - target) || (Math.abs(root.val - target) == Math.abs(closest - target) && root.val < target)){ 21 closest = root.val; 22 } 23 24 if(root.val < target){ 25 root = root.right; 26 }else if(root.val > target){ 27 root = root.left; 28 }else{ 29 return root.val; 30 } 31 } 32 return closest; 33 } 34 }