# LeetCode ---- 二叉树的层次遍历

3
/ \
9 20
/ \
15 7

[
[3],
[9,20],
[15,7]
]

public class LevelOrder {

@Test
public void levelOrder() {
TreeNode treeNode = new TreeNode(3);
treeNode.left = new TreeNode(9);
treeNode.right = new TreeNode(20);
treeNode.right.left = new TreeNode(15);
treeNode.right.right = new TreeNode(7);
List<List<Integer>> lists = levelOrder(treeNode);
Assert.assertArrayEquals(new Integer[]{3}, lists.get(0).toArray());
Assert.assertArrayEquals(new Integer[]{9,20}, lists.get(1).toArray());
Assert.assertArrayEquals(new Integer[]{15,7}, lists.get(2).toArray());
}

public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> arrayLists = new ArrayList<>();

if (root == null) {
return new ArrayList<>();
}

Queue<TreeNode> queue = new ArrayBlockingQueue<>(100);

while (queue.size() != 0) {
ArrayList<Integer> ints = new ArrayList<>();

int size = queue.size();
for (int i = 0; i < size; i++) {
TreeNode node = queue.poll();
if (node != null) {
}
if (node.left != null) {
}
if (node.right != null) {
}
}

}

return arrayLists;
}
}

• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120