Advertisement
valiamaximova1

TreeBFS

Apr 2nd, 2020
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.58 KB | None | 0 0
  1. import java.util.ArrayList;
  2. import java.util.LinkedList;
  3. import java.util.List;
  4. import java.util.Queue;
  5.  
  6. public class MyTreeBFS {
  7.  
  8.     public static void main(String[] args) {
  9.         Node<String> root = createTree();
  10.         System.out.print("First Search: ");
  11.  
  12.         levelOrderQueue(root);
  13.  
  14.     }
  15.  
  16.     private static Node<String> createTree() {
  17.         Node<String> root = new Node<>("Пенка и Велислав -->");
  18.  
  19.         Node<String> father = new Node<String>("Валентин -->");
  20.         root.left = father;
  21.  
  22.         Node<String> sister = new Node<String>("Олимпия -->");
  23.         root.left.left = sister;
  24.  
  25.         Node<String> me = new Node<String>("Валентина");
  26.         root.left.right = me;
  27.  
  28.  
  29.         return root;
  30.     }
  31.  
  32.     public static void levelOrderQueue(Node root) {
  33.         Queue<Node> q = new LinkedList<Node>();
  34.         if (root == null)
  35.             return;
  36.         q.add(root);
  37.         while (!q.isEmpty()) {
  38.             Node n = q.remove();
  39.             System.out.print(n.data + " ");
  40.             if (n.left != null)
  41.                 q.add(n.left);
  42.             if (n.right != null)
  43.                 q.add(n.right);
  44.  
  45.         }
  46.     }
  47.  
  48.     static class Node<T> {
  49.  
  50.         private T data = null;
  51.  
  52.         private List<Node<T>> children = new ArrayList<>();
  53.         Node<T> left;
  54.         Node<T> right;
  55.  
  56.         public Node(T data) {
  57.             this.data = data;
  58.             this.left = null;
  59.             this.right = null;
  60.         }
  61.  
  62.         public T getData() {
  63.             return data;
  64.         }
  65.  
  66.     }
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement