Description
Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
Example
Given binary tree {3,9,20,#,#,15,7}
,
3 / \ 9 20 / \ 15 7
return its level order traversal as:
[ [3], [9,20], [15,7] ]
Challenge
Challenge 1: Using only 1 queue to implement it.
Challenge 2: Use DFS algorithm to do it.
Solution
1. BFS(宽度优先搜索)
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/**
* @param root: A Tree
* @return: Level order a list of lists of integer
*/
public List<List<Integer>> levelOrder(TreeNode root) {
// write your code here
List<List<Integer>> result = new ArrayList<>();
if (root == null) {
return result;
}
//层序遍历要用到的数据结构是queue,且java中队列实现多用LinkedList但不能用ArrayList
Queue<TreeNode> queue = new LinkedList<TreeNode>();
//add()和remove()方法在失败的时候会抛出异常(不推荐),一般使用offer()和poll()方法
queue.offer(root);
while (!queue.isEmpty()) {
ArrayList<Integer> level = new ArrayList<>();
int size = queue.size();
for (int i = 0; i < size; i++) { //得到每层的结果就要遍历每层,如果不需要按层分开,则可去掉这层for循环
TreeNode head = queue.poll(); //头出队,将这个节点为根的左右节点加入队列
level.add(head.val);
if (head.left != null) {
queue.offer(head.left);
}
if (head.right != null) {
queue.offer(head.right);
}
}
result.add(level); //每层遍历之后添加一次level到result中
}
return result; //队列为空后返回result
}
}