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

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

    This can be done using a Queue and a ArrayList. Queue will be used to perform a breadth first search on the tree. ArrayList will be used to store the element of the tree in breadth first order. Here is the code to implement the same

    Queue queue = new LinkedList();
    ArrayList list = new ArrayList();
    int i =0;
    public Node findNextRightNode(Node root,int key)
    {
        System.out.print("The breadth first search on Tree : \t");      
        if(root == null)
            return null;
    
        queue.clear();
        queue.add(root);
    
        while(!queue.isEmpty() )
        {
            Node node = (Node)queue.remove();
            System.out.print(node.data + " ");
            list.add(node);
            if(node.left != null) queue.add(node.left);
            if(node.right !=null) queue.add(node.right);            
        }
    
        Iterator iter = list.iterator();
        while(iter.hasNext())
            {
                if(((Node)iter.next()).data == key)
                {
                    return ((Node)iter.next());
                }               
            }
    
        return null;
    }
    

提交回复
热议问题