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

后端 未结 10 994
刺人心
刺人心 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:26

    Below one works with different samples which I have.

    public Node findNearest(Node root, int k) {
        if (root == null) {
            return null;
        }
        int minDiff = 0;
        Node minAt = root;
        minDiff = Math.abs(k - root.data);
    
        while (root != null) {
            if (k == root.data) {
                return root;
            }
            if (k < root.data) {
                minAt = updateMin(root, k, minDiff, minAt);
                root = root.left;
            } else if (k > root.data) {
                minAt = updateMin(root, k, minDiff, minAt);
                root = root.right;
            }
    
        }
        return minAt;
    }
    
    private Node updateMin(Node root, int k, int minDiff, Node minAt) {
        int curDif;
        curDif = Math.abs(k - root.data);
        if (curDif < minDiff) {
            minAt = root;
        }
        return minAt;
    }
    

提交回复
热议问题