270. Closest Binary Search Tree Value

问题来自 270. Closest Binary Search Tree Value


我们只需要按照普通搜索二叉树的方法搜索即可,搜索的过程中不断更新值。


class Solution {
public:
    int closestValue(TreeNode* root, double target) {
        if(root == NULL) return -1;
        int result = root->val;
        while(root != NULL)
        {
            if(fabs(target-result) > fabs(target-root->val))
                result = root->val;
            if(target < root->val)
                root = root->left;
            else
                root = root->right;
        }
        return result;
    }
};

Java:

public class Solution {
    public int closestValue(TreeNode root, double target) {
        if(root == null) return 0;
        int result = root.val;
        while(root != null)
        {
            if(Math.abs(target-root.val) < Math.abs(target-result))
                result = root.val;
            if(target < root.val)
                root = root.left;
            else
                root = root.right;
        }
        return result;
    }
}

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.