|
1 | 1 | package com.thealgorithms.datastructures.trees;
|
2 | 2 |
|
3 |
| -public class LevelOrderTraversal { |
4 |
| - |
5 |
| - class Node { |
6 |
| - |
7 |
| - int data; |
8 |
| - Node left, right; |
9 |
| - |
10 |
| - public Node(int item) { |
11 |
| - data = item; |
12 |
| - left = right = null; |
13 |
| - } |
14 |
| - } |
| 3 | +import java.util.ArrayList; |
| 4 | +import java.util.LinkedList; |
| 5 | +import java.util.List; |
| 6 | +import java.util.Queue; |
15 | 7 |
|
16 |
| - // Root of the Binary Tree |
17 |
| - Node root; |
18 |
| - |
19 |
| - public LevelOrderTraversal(Node root) { |
20 |
| - this.root = root; |
21 |
| - } |
22 |
| - |
23 |
| - /* function to print level order traversal of tree*/ |
24 |
| - void printLevelOrder() { |
25 |
| - int h = height(root); |
26 |
| - int i; |
27 |
| - for (i = 1; i <= h; i++) { |
28 |
| - printGivenLevel(root, i); |
29 |
| - } |
30 |
| - } |
| 8 | +public class LevelOrderTraversal { |
31 | 9 |
|
32 |
| - /* Compute the "height" of a tree -- the number of |
33 |
| - nodes along the longest path from the root node |
34 |
| - down to the farthest leaf node.*/ |
35 |
| - int height(Node root) { |
| 10 | + static List<List<Integer>> traverse(BinaryTree.Node root) { |
36 | 11 | if (root == null) {
|
37 |
| - return 0; |
38 |
| - } else { |
39 |
| - /** |
40 |
| - * Return the height of larger subtree |
41 |
| - */ |
42 |
| - return Math.max(height(root.left), height(root.right)) + 1; |
| 12 | + return List.of(); |
43 | 13 | }
|
44 |
| - } |
45 | 14 |
|
46 |
| - /* Print nodes at the given level */ |
47 |
| - void printGivenLevel(Node root, int level) { |
48 |
| - if (root == null) { |
49 |
| - return; |
50 |
| - } |
51 |
| - if (level == 1) { |
52 |
| - System.out.print(root.data + " "); |
53 |
| - } else if (level > 1) { |
54 |
| - printGivenLevel(root.left, level - 1); |
55 |
| - printGivenLevel(root.right, level - 1); |
| 15 | + List<List<Integer>> result = new ArrayList<>(); |
| 16 | + |
| 17 | + Queue<BinaryTree.Node> q = new LinkedList<>(); |
| 18 | + q.add(root); |
| 19 | + while (!q.isEmpty()) { |
| 20 | + int nodesOnLevel = q.size(); |
| 21 | + List<Integer> level = new LinkedList<>(); |
| 22 | + for (int i = 0; i < nodesOnLevel; i++) { |
| 23 | + BinaryTree.Node tempNode = q.poll(); |
| 24 | + level.add(tempNode.data); |
| 25 | + |
| 26 | + if (tempNode.left != null) { |
| 27 | + q.add(tempNode.left); |
| 28 | + } |
| 29 | + |
| 30 | + if (tempNode.right != null) { |
| 31 | + q.add(tempNode.right); |
| 32 | + } |
| 33 | + } |
| 34 | + result.add(level); |
56 | 35 | }
|
| 36 | + return result; |
57 | 37 | }
|
58 | 38 | }
|
0 commit comments