How do implement a breadth first traversal?

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

    public static boolean BFS(ListNode n, int x){
            if(n==null){
               return false;
           }
    Queue> q = new Queue>();
    ListNode tmp = new ListNode(); 
    q.enqueue(n);
    tmp = q.dequeue();
    if(tmp.val == x){
        return true;
    }
    while(tmp != null){
        for(ListNode child: n.getChildren()){
            if(child.val == x){
                return true;
            }
            q.enqueue(child);
        }
    
        tmp = q.dequeue();
    }
    return false;
    }
    

提交回复
热议问题