Advertisement
petrovwa

Homework

Apr 8th, 2020
257
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.06 KB | None | 0 0
  1. import java.util.LinkedList;
  2. import java.util.Queue;
  3. public class T_BFS {
  4.     public void levelOrderQueue(Node root) {
  5.         Queue<Node> q = new LinkedList<Node>();
  6.         if (root == null)
  7.             return;
  8.         q.add(root);
  9.         while (!q.isEmpty()) {
  10.             Node n = (Node) q.remove();
  11.             System.out.print(" " + n.data);
  12.             if (n.left != null)
  13.                 q.add(n.left);
  14.             if (n.right != null)
  15.                 q.add(n.right);
  16.         }
  17.     }
  18.     public static void main(String[] args) throws java.lang.Exception {
  19.         Node root = new Node("Динка и Стоян");
  20.         root.left = new Node("Николета и Динко");
  21.         root.right = new Node("Никола и Стоян");
  22.         T_BFS i = new T_BFS();
  23.         System.out.println("Breadth First Search : ");
  24.         i.levelOrderQueue(root);
  25.     }
  26. }
  27. class Node {
  28.     String data;
  29.     Node left;
  30.     Node right;
  31.     public Node(String data) {
  32.         this.data = data;
  33.         this.left = null;
  34.         this.right = null;
  35.     }
  36. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement