Burning Tree problem from geeks for geeks

38 Views Asked by At

I was doing "Burning Tree" problem over geeks for geeks platform, but my code giving wrong answer I tried doing dry run but am not able to identify what's wrong in my code. Can anyone please help in identifying the issue in below code?

Failing testcase input: 1 2 3 4 5 N 6 N N 7 8 N 9 10 11 N N N 12 N N N 13

Expected output: 8

Output i am getting from below code is 4.

class Node {
    int data;
    Node left;
    Node right;

    Node(int data) {
        this.data = data;
        left = null;
        right = null;
    }
}
public static int minTime(Node root, int target) 
{
    int  time = 0;
    
    if( root == null)
        return time;
    
    Map<Node, Node> map = new HashMap<>();
    HashSet<Node> visited = new HashSet<>();
    Queue<Node> q = new LinkedList<>();
    
    parentMap(root, map);
    
    Node burningNode = findTargetNode(root, target);
    
    if(burningNode != null) 
        q.offer(burningNode); // 7 8 2
    
    while(!q.isEmpty()){
        int qSize = q.size(); //1
        for(int i = 0 ; i < qSize ; i++){
            
            Node temp = q.poll(); //5
            visited.add(temp);
                
            if(temp.left != null && !visited.contains(temp))
            {
                q.offer(temp.left);
            }   
            if(temp.right != null && !visited.contains(temp))
            {
                q.offer(temp.right);
            }   
            if(map.containsKey(temp) && !visited.contains(map.get(temp)))
            {
                q.offer(map.get(temp));
            }
        }
        time++;
        
    }
    return time;
} 
private static void parentMap (Node node, Map<Node,Node> map){
    
    if ( node == null ) 
    {
        return ;
    }
    if ( node.left != null )
    {
        map.put(node.left, node);
    }
    if(node.right != null )
    {
        map.put(node.right, node);
    }    
    parentMap(node.left, map);
    parentMap(node.right, map);
    
}
private static Node findTargetNode(Node node, int target){
    
    if(node == null)
    {
        return null;
    }
    if(node.data == target)
    {
        return node;
    }   
    Node left = findTargetNode(node.left, target);
    Node right = findTargetNode(node.right, target);
    return left != null ? left : right;
}
0

There are 0 best solutions below