Hi, would you mind helping me in solving this problem?
Because I stuck now. The problem is to print a space in a binary tree (not binary search tree)
my current program can only output without appropriate spacing
so if input is : 4 7 8 9 2 0 3 1 5
the output will become
4
7 8
9 2 0 3
1 5
What the expected output is
4 7 8 9 2 0 3 1 5
actually the "/" space is not really compulsory, the problem is to print spaces
Here is my code contains 2 classes: TreeNode class and BinaryTree class
import java.io.*; public class TreeNode { public Object da; public TreeNode left; public TreeNode right; public TreeNode(Object newItem) { da = newItem; left = null; right = null; } public TreeNode(Object newItem, TreeNode leftNode, TreeNode rightNode) { da = newItem; left = leftNode; right = rightNode; } public void setItem(Object newItem) { da = newItem; } public Object getItem() { return da; } public void setLeft(TreeNode leftNode) { left = leftNode; } public TreeNode getLeft() { return left; } public void setRight(TreeNode rightNode) { right = rightNode; } public TreeNode getRight() { return right; } public int left (int i) { return 2*i; } public int right (int i) { return 2*i + 1; } public int parent (int i) { return (i-1)/2; } }
import java.util.*; class BinaryTree { public static void main(String args[]) { Scanner input = new Scanner(System.in); System.out.println("Enter the values to insert into the binary tree: "); String[] values = (input.nextLine()).split("\\s"); TreeNode root = null; Queue queue = new LinkedList(); TreeNode parent = null; for (int index = 0; index < values.length; index++) { if (root == null) { root = new TreeNode(values[index]); queue.add(root); } else { TreeNode node = new TreeNode(values[index]); if (index % 2 == 1) { parent = (TreeNode) queue.remove(); parent.setLeft(node); } else { parent.setRight(node); } queue.add(node); } } queue = new LinkedList(); queue.add(root); int maxNodes = 1; int countNodes = 0; while (queue.size() > 0 ) { TreeNode node = (TreeNode) queue.remove(); System.out.print(node.getItem().toString() + " "); countNodes++; if (countNodes == maxNodes) { System.out.println(); maxNodes = maxNodes * 2; countNodes = 0; } TreeNode leftChild = node.getLeft(); if (leftChild != null) queue.add(leftChild); TreeNode rightChild = node.getRight(); if (rightChild != null) queue.add(rightChild); } System.out.println(); } }
It can’t print like the real binary tree and I do not know how to make it accordingly.
Any suggestions?
Thanks a lot. =)