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.
recursive 的基本做法。
主要是要比较parent和left right的大小
那么可以分base:root(当前的)
和recursive的两种
/**
* 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) {
TreeNode tmp = target > root.val ? root.right : root.left;
if(tmp == null){
return root.val;//叶子节点直接return
}
int result = closestValue(tmp, target);
return Math.abs(root.val - target) > Math.abs(result - target) ? result : root.val;//比较parent和child
}
}