Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.ArrayList;
- import java.util.LinkedList;
- import java.util.List;
- import java.util.Queue;
- public class MyTreeBFS {
- public static void main(String[] args) {
- Node<String> root = createTree();
- System.out.print("First Search: ");
- levelOrderQueue(root);
- }
- private static Node<String> createTree() {
- Node<String> root = new Node<>("Пенка и Велислав -->");
- Node<String> father = new Node<String>("Валентин -->");
- root.left = father;
- Node<String> sister = new Node<String>("Олимпия -->");
- root.left.left = sister;
- Node<String> me = new Node<String>("Валентина");
- root.left.right = me;
- return root;
- }
- public static void levelOrderQueue(Node root) {
- Queue<Node> q = new LinkedList<Node>();
- if (root == null)
- return;
- q.add(root);
- while (!q.isEmpty()) {
- Node n = q.remove();
- System.out.print(n.data + " ");
- if (n.left != null)
- q.add(n.left);
- if (n.right != null)
- q.add(n.right);
- }
- }
- static class Node<T> {
- private T data = null;
- private List<Node<T>> children = new ArrayList<>();
- Node<T> left;
- Node<T> right;
- public Node(T data) {
- this.data = data;
- this.left = null;
- this.right = null;
- }
- public T getData() {
- return data;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement