How to find the closest element to a given key value in a binary search tree?

后端 未结 10 991
刺人心
刺人心 2020-12-25 14:58

Given a bst with integer values as keys how do I find the closest node to that key in a bst ? The BST is represented using a object of nodes (Java). Closest will be for eg 4

10条回答
  •  無奈伤痛
    2020-12-25 15:15

    Here is the working solution in java which uses the characteristics of BST and additional integer to store minimum difference

    public class ClosestValueBinaryTree {
            static int closestValue;
    
            public static void closestValueBST(Node22 node, int target) {
                if (node == null) {
                    return;
                }
                if (node.data - target == 0) {
                    closestValue = node.data;
                    return;
                }
                if (Math.abs(node.data - target) < Math.abs(closestValue - target)) {
                    closestValue = node.data;
                }
                if (node.data - target < 0) {
                    closestValueBST(node.right, target);
                } else {
                    closestValueBST(node.left, target);
                }
            }
        }
    

    Run time complexity - O(logN)

    Space time complexity - O(1)

提交回复
热议问题