Advertisement
Mariyan17320

Iliev's homework- BFS 17320

Apr 9th, 2020
265
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.50 KB | None | 0 0
  1. import java.util.LinkedList;
  2. import java.util.Queue;
  3.  
  4. public class BFS {
  5.  
  6.     public void levelOrderQueue(Node root) {
  7.         Queue<Node> qund = new LinkedList<Node>();
  8.         if (root == null)
  9.             return;
  10.         qund.add(root);
  11.         while (!qund.isEmpty()) {
  12.             Node nde = (Node) qund.remove();
  13.             System.out.print(" " + nde.data);
  14.             if (nde.left != null)
  15.                 qund.add(nde.left);
  16.             if (nde.down != null)
  17.                 qund.add(nde.down);
  18.             if (nde.right != null)
  19.                 qund.add(nde.right);
  20.         }
  21.     }
  22.     public static void main(String[] args) throws java.lang.Exception {
  23.         Node root=new Node(1);
  24.         root.left=new Node(2);
  25.         root.down=new Node(3);
  26.         root.right=new Node(4);
  27.         root.left.left=new Node(5);
  28.         root.left.down=new Node(6);
  29.         root.right.down=new Node(7);
  30.         root.right.right=new Node(8);
  31.         root.left.left.left=new Node(9);
  32.         root.left.left.down=new Node(10);
  33.         root.right.down.down=new Node(11);
  34.         root.right.down.right=new Node(12);
  35.  
  36.         BFS i = new BFS();
  37.         System.out.println("BFS:");
  38.         i.levelOrderQueue(root);
  39.     }
  40.     static class Node {
  41.         int data;
  42.         Node left;
  43.         Node right;
  44.         Node down;
  45.         public Node(int data) {
  46.             this.data = data;
  47.             this.left = null;
  48.             this.right = null;
  49.             this.down = null;
  50.         }
  51.     }
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement