1

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);
        }

}
2
  • Pass a StringBuilder in as a parameter and append to it as you visit each node during the BFS. Commented May 5, 2014 at 4:33
  • what would it look like without a paremeter? Commented May 5, 2014 at 4:43

1 Answer 1

1

just define a String variable and add the node.data to it while searching.

/**
 * 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>>();
 String traversal = "";
 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 + " ");
     traversal += node.data + " ";
     if(node.left != null) queue.add(node.left);
     if(node.right != null) queue.add(node.right);
    }
    return traversal;
}
Sign up to request clarification or add additional context in comments.

5 Comments

I get an error on if(node.right != null) queue.add(node.rightjava and Node<E> node = queue*remove();
whats node.rightjava and whats with the queue*remove()?
this time it should be ok.
Here's my test, is this what it's suppose to print out afterwards? multipleTree = new BinarySearchTree<Integer>(); multipleTree.add(100); multipleTree.add(50); multipleTree.add(150); multipleTree.add(75); multipleTree.add(25); multipleTree.add(125); multipleTree.add(175); assertEquals("100 50 150 25 75 125 175" , multipleTree.breadthFirstOrder());
you can check your output info, it's the same as your print info, and I believe it's what you want.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.