So I've figured out how to do a bread-first order for a binary search tree but I need to return a String with a breadth-first order traversal of the tree, how do I do that?
My Code:
/**
* Returns a breadth-first order String of tree elements.
*
* @return a String with a breadth-first order traversal of the tree
*/
public String breadthFirstOrder() {
Queue<Node<E>> queue = new LinkedList<Node<E>>();
if (root == null)
System.out.println("Empty tree");
queue.clear();
queue.add(root);
while(!queue.isEmpty()){
Node<E> node = queue.remove();
System.out.print(node.data + " ");
if(node.left != null) queue.add(node.left);
if(node.right != null) queue.add(node.right);
}
}
StringBuilderin as a parameter and append to it as you visit each node during the BFS.