Number of Visible Nodes

	  class Node {
		    int data; 
		    Node left; 
		    Node right; 
		    Node() {
		      this.data = 0; 
		      this.left = null; 
		      this.right = null; 
		    }
		    Node(int data) {
		      this.data = data; 
		      this.left = null; 
		      this.right = null; 
		    }
		  }
		  
	
	int visibleNodes(Node root) {
       Queue<Node> q = new LinkedList<Node>();
       Queue<Integer> level = new LinkedList<Integer>();
       q.add(root);
       level.add(1);
       int count = 0;
       while(!q.isEmpty()) {
    	   Node n = q.poll();
    	    count = level.poll();
    	   if(n.right != null ) {
    		   q.add(n.right);
    		   level.add(count+1);
    	   }
    	   if(n.left != null ) {
    		   q.add(n.left);
    		   level.add(count+1);
    	   }
       }
       return count;
	}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s