Reputation: 21
I'm trying to make a class that prints my binary tree level by level.
I have here on my code classes that (1) inserts elements on my binary tree, (2) prints in an in-order, (3) prints in a post-order, (4) prints in a pre-order. And I need to create one more class that prints my binary trees in a tree-like structure (or pyramid like) I want to create a class that prints the elements of my binary tree like this:
Thank you!
public class MyBinaryTree {
static class Node{
char data;
Node left;
Node right;
Node(char data){
left = right = null;
this.data = data;
}
}
Node root;
MyBinaryTree(){
root = null;
}
public void insertElements() {
Scanner scan = new Scanner(System.in);
String inputStr = new String();
System.out.print("Input elements:");
inputStr = scan.nextLine();
for(int i = 0; i < inputStr.length(); i++) {
Insert(inputStr.charAt(i));
}
}
public void Insert (char data) {
root = Insert(root, data);
numOfNodes++;
}
Node Insert (Node node, char data) {
if (node == null) {
node = new Node(data);
} else {
if (data <= node.data) {
node.left = Insert(node.left, data);
} else {
node.right = Insert(node.right, data);
}
}
return node;
}
}
Upvotes: 2
Views: 1132
Reputation: 772
I imagine that you search something as this:
The solution has some files, one interface and one utility class with much code. So I consider that it's not a good idea copy all code here.
I'll leave the link of the solution. Read de the file readme and follow the instructions step by step to integrate the solution to your binary tree project.
Repository solution: https://github.com/marcosquispesb/arbolesprint
(Sorry for my english, I agree fix me please)
I Hope I've helped. Greetings.
Upvotes: -1
Reputation: 156
Queue is best if you want to print level by level
void printLevelOrder() {
Queue<Node> queue = new LinkedList<Node>();
queue.add(root);
queue.add(null);
while (!queue.isEmpty()) {
Node temp = queue.poll();
if(temp!=null)
System.out.print(temp.data + " ");
if(temp == null) {
System.out.println();
if(queue.isEmpty()) break;
queue.add(null);
continue;
}
/*Enqueue left child */
if (temp.left != null) {
queue.add(temp.left);
}
/*Enqueue right child */
if (temp.right != null) {
queue.add(temp.right);
}
}
}
Note: Adding null to queue is mentioning next line.
Upvotes: 3