Leetcode

270. Closest Binary Search Tree Value

by hooni posted May 01, 2020
?

단축키

Prev이전 문서

Next다음 문서

ESC닫기

크게 작게 위로 아래로 댓글로 가기 인쇄

/**
 * 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) {
        Queue<TreeNode> queue = new LinkedList<>();
        double minDiff = Double.MAX_VALUE;
        int minValue = root.val;
        
        queue.offer(root);
        while(queue.size() > 0){
            int size = queue.size();
            for(int i=0; i<size; i++){
                TreeNode node = queue.poll();
                if(node.left != null){
                    queue.offer(node.left);
                }
                if(node.right != null){
                    queue.offer(node.right);
                }
                
                if(minDiff > Math.abs(node.val - target)){
                    minDiff = Math.abs(node.val - target);
                    minValue = node.val;
                }
            }
        }
        
        return minValue;
    }
}


/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    double minDiff;
    int minValue;

    public int closestValue(TreeNode root, double target) {
        minDiff = Double.MAX_VALUE;
        minValue = root.val;
        
        findMinDiff(root, target);
        
        return minValue;
    }

    public void findMinDiff(TreeNode node, double target){
        if(node == null){
            return;
        }
        
        if(minDiff > Math.abs(node.val - target)){
            minDiff = Math.abs(node.val - target);
            minValue = node.val;
        }
        
        findMinDiff(node.left, target);
        findMinDiff(node.right, target);
    }
}

[문제] https://leetcode.com/problems/closest-binary-search-tree-value/