yokostan / Leetcode-Solutions

Doing exercise on Leetcode. Carry on!
0 stars 3 forks source link

Leetcode #270. Closest Binary Search Tree Value #238

Open yokostan opened 5 years ago

yokostan commented 5 years ago

Easy version.

class Solution {
    public int closestValue(TreeNode root, double target) {
        int res = root.val;

        while (root != null) {
            if (Math.abs(target - root.val) < Math.abs(target - res)) {
                res = root.val;
            }
            if (root.val > target) root = root.left;
            else root = root.right;
        }

        return res;
    }
}

well, I thought about in-order traversal and the double kinda confused me for a while, but the solution seems so easy by following the logic to judge whether it's smaller and righter and go to one branch. And also, comparing int with double is valid, our algorithm will cast int to double before comparison. But using == or != is not valid.