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

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

    void closestNode(Node root, int k , Node result) {
        if(root == null) 
        {
           return;      //currently result is null , so it  will be the result
        }
        if(result == null || Math.abs(root.data - k) < Math.abs(result.data - k) )
        {
          result == root;
        }
        if(k < root.data)
        {
        closestNode(root.left, k, result)
        } 
        else 
        {
            closestNode(root.right, k, result);
        }
    
    }
    

提交回复
热议问题