Find the closest element in the binary search tree

Given abinary search treeand a target node K. The task is to find the node with minimum absolute difference with given target value K.

Examples:

// For above binary search tree
Input  :  k = 4
Output :  4

Input  :  k = 18
Output :  17

Input  :  k = 12
Output :  9

Solution)

Use the recursive method and helper function, we have to find the closest element with the current closest and key.

public class TreeNode {
    int val;
    TreeNode left, right;
    TreeNode(int val) {
        this.val = val;
        this.left = this.right = null;
    }
}
public int helper(TreeNode node, int k, int closest, int val) {
    if (root == null) return val;
    if (root.val == k) return root.val;
    if (Math.abs(root.val-k) < closest) {
        closest = Math.abs(root.val-k);
        val = root.val;
    }
    if (root.val < k)
        return helper(root.right, k, closest, val);
    else
        return helper(root.left, k, closest, val);
}

public int findClosest(TreeNode root, int k) {
    int closest = Integer.MAX_VALUE, val = -1;
    return helper(root, k, closest, val);
}

results matching ""

    No results matching ""