forked from gouthampradhan/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
BinarayTreeLevelOrderTraversal.java
94 lines (86 loc) · 2.61 KB
/
BinarayTreeLevelOrderTraversal.java
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package breadth_first_search;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;
/**
* Created by gouthamvidyapradhan on 13/03/2017.
* Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
* <p>
* For example:
* Given binary tree [3,9,20,null,null,15,7],
* 3
* / \
* 9 20
* / \
* 15 7
* return its level order traversal as:
* [
* [3],
* [9,20],
* [15,7]
* ]
*/
public class BinarayTreeLevelOrderTraversal {
public static class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
private class LevelNode {
TreeNode node;
int level;
LevelNode(TreeNode node, int level) {
this.node = node;
this.level = level;
}
}
/**
* Main method
*
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
TreeNode root = new TreeNode(2);
root.left = new TreeNode(3);
root.right = new TreeNode(4);
root.right.right = new TreeNode(5);
root.right.left = new TreeNode(4);
root.right.left.right = new TreeNode(8);
root.right.left.left = new TreeNode(7);
root.right.left.left.right = new TreeNode(10);
root.right.left.left.left = new TreeNode(9);
List<List<Integer>> result = new BinarayTreeLevelOrderTraversal().levelOrder(root);
}
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> result = new ArrayList<>();
if (root == null) return result;
Queue<LevelNode> queue = new ArrayDeque<>();
queue.offer(new LevelNode(root, 0));
int currentLevel = 0;
List<Integer> row = new ArrayList<>();
while (!queue.isEmpty()) {
LevelNode levelNode = queue.poll();
if (levelNode.node != null) {
if (levelNode.level != currentLevel) {
result.add(row);
row = new ArrayList<>();
currentLevel++;
}
row.add(levelNode.node.val);
TreeNode left = levelNode.node.left;
TreeNode right = levelNode.node.right;
LevelNode lNodeL = new LevelNode(left, levelNode.level + 1);
LevelNode lNodeR = new LevelNode(right, levelNode.level + 1);
queue.offer(lNodeL);
queue.offer(lNodeR);
}
}
result.add(row);
return result;
}
}