How do implement a breadth first traversal?

前端 未结 9 1336
萌比男神i
萌比男神i 2020-11-28 21:34

This is what I have. I thought pre-order was the same and mixed it up with depth first!

import java.util.LinkedList;
import java.util.Queue;

public class Ex         


        
9条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-28 22:02

    It doesn't seem like you're asking for an implementation, so I'll try to explain the process.

    Use a Queue. Add the root node to the Queue. Have a loop run until the queue is empty. Inside the loop dequeue the first element and print it out. Then add all its children to the back of the queue (usually going from left to right).

    When the queue is empty every element should have been printed out.

    Also, there is a good explanation of breadth first search on wikipedia: http://en.wikipedia.org/wiki/Breadth-first_search

提交回复
热议问题