How do implement a breadth first traversal?

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

    public void breadthFirstSearch(Node root, Consumer c) {
        List queue = new LinkedList<>();
    
        queue.add(root);
    
        while (!queue.isEmpty()) {
            Node n = queue.remove(0);
            c.accept(n.value);
    
            if (n.left != null)
                queue.add(n.left);
            if (n.right != null)
                queue.add(n.right);
        }
    }
    

    And the Node:

    public static class Node {
        String value;
        Node left;
        Node right;
    
        public Node(final String value, final Node left, final Node right) {
            this.value = value;
            this.left = left;
            this.right = right;
        }
    }
    

提交回复
热议问题