-
Notifications
You must be signed in to change notification settings - Fork 3
/
Binary-Tree-Level-Order-Traversal
55 lines (46 loc) · 1.24 KB
/
Binary-Tree-Level-Order-Traversal
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package com.tree.traversal.iterative;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
public class LevelOrderTraversal {
static List<Integer> result;
public static void main(String[] args) {
TreeNode left = new TreeNode(2);
TreeNode right = new TreeNode(3);
TreeNode root = new TreeNode(1, left, right);
left.right = new TreeNode(4, new TreeNode(6), new TreeNode(7));
right.left = new TreeNode(5, null, new TreeNode(8));
result = new ArrayList<Integer>();
System.out.println("Level Order Traversal : " + levelOrderTraversal(root));
}
private static List<Integer> levelOrderTraversal(TreeNode root) {
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
while(!queue.isEmpty()) {
int size = queue.size();
while(size-- > 0) {
TreeNode current = queue.remove();
result.add(current.val);
if(current.left!=null) queue.add(current.left);
if(current.right != null) queue.add(current.right);
}
}
return result;
}
}
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {
}
TreeNode(int val) {
this.val = val;
}
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}