Leetcode - 270. Closest Binary Search Tree Value

숲사람·2022년 9월 18일
0

멘타트 훈련

목록 보기
148/237

문제

주어진 target값이 트리 노드중에 어떤값과 가장 가까운지 찾아라.

Input: root = [4,2,5,1,3], target = 3.714286
Output: 4

해결

해당 값을 binary search하여 찾음. (해설 답안은 더 간결한데 확인해볼것 https://leetcode.com/problems/closest-binary-search-tree-value/solution/)

class Solution {
public:
    int closestValue(TreeNode* root, double target) {
        int left_most = -1;
        int right_lest = -1;
        TreeNode *node = root;
        while (node) {
            if (target < (double)node->val) {
                right_lest = node->val;
                node = node->left;
            } else if ((double)node->val < target) {
                left_most = node->val;
                node = node->right;
            } else { // node->val == target
                return node->val;
            }
        }            
        if (left_most == -1 && right_lest != -1)
            return right_lest;
        else if (left_most != -1 && right_lest == -1)
            return left_most;
        // left_most   target  right_lest
        double a = right_lest - (double)target;
        double b = (double)target - left_most;
        return a > b ? left_most : right_lest;
    }
};
profile
기록 & 정리 아카이브 용도 (보다 완성된 글은 http://soopsaram.com/documentudy)

0개의 댓글