congr / world

2 stars 1 forks source link

LeetCode : 270. Closest Binary Search Tree Value #475

Closed congr closed 5 years ago

congr commented 5 years ago

https://leetcode.com/problems/closest-binary-search-tree-value/

image

congr commented 5 years ago

Iterative

/**
 * 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) {
        TreeNode closest = root;

        while (root != null) {
            double cur = Math.abs(root.val - target);
            double pre = Math.abs(closest.val - target);

            if (cur < pre) closest = root;

            if (root.val < target) root = root.right;
            else if (root.val > target) root = root.left;
            else return root.val;
        }

        return closest.val;
    }
}
congr commented 5 years ago

Recursive

/**
 * 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) {
        int val = root.val;
        if (root.val > target && root.left != null) val = closestValue(root.left, target);
        else if (root.val < target && root.right != null) val = closestValue(root.right, target);

        return Math.abs(root.val - target) < Math.abs(val - target) ? root.val : val; 
    }
}