Advertisement
Sasho_Cvetkov17101

Untitled

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