How do implement a breadth first traversal?

前端 未结 9 1332
萌比男神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:07

    //traverse
    public void traverse()
    {
        if(node == null)
            System.out.println("Empty tree");
        else
        {
            Queue q= new LinkedList();
            q.add(node);
            while(q.peek() != null)
            {
                Node temp = q.remove();
                System.out.println(temp.getData());
                if(temp.left != null)
                    q.add(temp.left);
                if(temp.right != null)
                    q.add(temp.right);
            }
        }
    }
    

    }

提交回复
热议问题