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.

一刷
题解:
方法1,递归
递归的原理是,如果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) {
       int a = root.val;
        TreeNode kid = a < target? root.right: root.left;
        if(kid == null) return a;
        int b = closestValue(kid, target);
        if(Math.abs(a-target)

方法二,iteration

/**
 * 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) {
        int closest = root.val;
        while(root!=null){
            if(Math.abs(closest-target) >= Math.abs(root.val - target))
                closest = root.val;
            root = target < root.val? root.left: root.right;
        }
        return closest;
    }
}

二刷
同上

/**
 * 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((double)root.val == target) return root.val;
        if(targetroot.val && root.right == null) return root.val;
        if(target root.val){
            int right = closestValue(root.right, target);
            if(Math.abs(root.val - target)< Math.abs(right - target))
                return root.val;
            else return right;
        }
        return 0;
    }
}

你可能感兴趣的:(270. Closest Binary Search Tree Value)