Input Problem- Tree Left View

Not able to get how to take input for the tree. Here’s my code-

import java.util.*;
public class Main {
public static void main(String args[]) {

}

}

class BT {
private class Node {
int data;
Node left;
Node right;
}

private Node root;

public void buildTree() {
	Queue<Node> queue = new LinkedList<>();

	queue.add(this.root);
	while(!queue.isEmpty()) {
		Node rv = queue.removeFirst();
		System.out.print(rv.data + " ");
		
		if(rv.left == -1) {
			return null;
		} else {
			queue.add(rv.left);
		}

		if(rv.right == -1) {
			return null;
		} else {
			queue.add(rv.right);
		}
	}
}

int max_level = 0;

public void leftView() {
	leftView(this.root, 1);
}

private void leftView(Node node, int level) {
	if(max_level < level) {
		System.out.print(node.data + "");
		max_level = level;
	}

	leftView(node.left, level+1);
	leftView(node.right, level+1);
}

}

@S19CRXN0023,
your logic was correct in leftview function. https://ide.codingblocks.com/s/221239 here is the complete code.

Since you are not using buffered reader in case the queue isn’t empty and the input string is finished. It will throw a run time error. For that use .hasNextInt() to check. If the next input is not an int, it will break and return the root node as it would mean the input is over.

hasNext function returns true if and only if this scanner’s next token is a valid Int value. In this case incase the next input is " " or something else, it will break and prevent runtime errors

I’m not able to understand the changes you applied.

What I had written was also the code for levelOrder traversal.

@S19CRXN0023,

FIrst in the main function, create an object of the scanner class. Pass that scanner class onto the constructor of our class BT.

public BT(Scanner s) { 
	this.root = this.buildTree(s);
} 

Here we call the buildTree function which will create our tree and return to us a node, which will be our root node.

In the buildtree method:
Take input of data and create a node. If the input is -1, we return null.
After that we add the node to our queue. And enter a while loop which runs until our queue is empty.

We store the first element in our queue as rv.
The poll() method of queue returns and removes the element at the front the container. It deletes the element in the container. The method does not throws an exception when the Queue is empty, it returns null instead.

Now we use hasNext to check if the next input is int or not. hasNext function returns true if and only if this scanner’s next token is a valid Int value. In this case incase the next input is " " or something else, it will break and prevent runtime errors

So if the input is an integer and its not -1, we add that node to the left of rv.
And do the same thing to add a node to the right of rv .

At the end we just return the initial node that we create which was this (Node node = new Node(data);).